KeyObservationRegistry.swift 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import Foundation
  2. /// A protocol used for adding and removing key observations
  3. public protocol KeyObservationRegistry {
  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 key: Unique key to identify the object in the cache
  10. - Parameter closure: Observation closure
  11. - Returns: Token used to cancel the observation and remove the observation closure
  12. */
  13. @discardableResult
  14. func addObserver<O: AnyObject>(
  15. _ observer: O,
  16. forKey key: String,
  17. closure: @escaping (O, S, KeyChange<S.T>) -> Void
  18. ) -> ObservationToken
  19. /**
  20. Removes observer by the given key.
  21. - Parameter key: Unique key to identify the object in the cache
  22. */
  23. func removeObserver(forKey key: String)
  24. /// Removes all registered key observers
  25. func removeAllKeyObservers()
  26. }
  27. // MARK: - KeyChange
  28. public enum KeyChange<T> {
  29. case edit(before: T?, after: T)
  30. case remove
  31. }
  32. extension KeyChange: Equatable where T: Equatable {
  33. public static func == (lhs: KeyChange<T>, rhs: KeyChange<T>) -> Bool {
  34. switch (lhs, rhs) {
  35. case (.edit(let before1, let after1), .edit(let before2, let after2)):
  36. return before1 == before2 && after1 == after2
  37. case (.remove, .remove):
  38. return true
  39. default:
  40. return false
  41. }
  42. }
  43. }