StorageObservationRegistry.swift 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import Foundation
  2. /// A protocol used for adding and removing storage observations
  3. public protocol StorageObservationRegistry {
  4. associatedtype S: StorageAware
  5. /**
  6. Registers observation closure which will be removed automatically
  7. when the weakly captured observer has been deallocated.
  8. - Parameter observer: Any object that helps determine if the observation is still valid
  9. - Parameter closure: Observation closure
  10. - Returns: Token used to cancel the observation and remove the observation closure
  11. */
  12. @discardableResult
  13. func addStorageObserver<O: AnyObject>(
  14. _ observer: O,
  15. closure: @escaping (O, S, StorageChange) -> Void
  16. ) -> ObservationToken
  17. /// Removes all registered key observers
  18. func removeAllStorageObservers()
  19. }
  20. // MARK: - StorageChange
  21. public enum StorageChange: Equatable {
  22. case add(key: String)
  23. case remove(key: String)
  24. case removeAll
  25. case removeExpired
  26. }
  27. public func == (lhs: StorageChange, rhs: StorageChange) -> Bool {
  28. switch (lhs, rhs) {
  29. case (.add(let key1), .add(let key2)), (.remove(let key1), .remove(let key2)):
  30. return key1 == key2
  31. case (.removeAll, .removeAll), (.removeExpired, .removeExpired):
  32. return true
  33. default:
  34. return false
  35. }
  36. }