Created
August 4, 2019 15:00
-
-
Save laevandus/e47478f8034d4e3ebee1d962e2e2530e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension KeyValueObservable { | |
@discardableResult func addObserver<Observer: AnyObject, Value>(_ observer: Observer, keyPath: KeyPath<Self, Value>, options: Observation.Options, handler: @escaping (Observer, Value) -> Void) -> Observation { | |
let observation = Observation() | |
let observationHandler: (PartialKeyPath<Self>) -> Bool = { [weak self, weak observer] changedKeyPath in | |
guard let self = self else { return false } | |
guard let observer = observer else { return false } | |
guard changedKeyPath == keyPath else { return true } | |
handler(observer, self[keyPath: keyPath]) | |
return true | |
} | |
observationStore.observationInfos[observation] = observationHandler | |
if options.contains(.initial) { | |
handler(observer, self[keyPath: keyPath]) | |
} | |
return observation | |
} | |
func removeObservation(_ observation: Observation) { | |
observationStore.observationInfos.removeValue(forKey: observation) | |
} | |
func didChangeValue(for keyPath: PartialKeyPath<Self>) { | |
observationStore.observationInfos = observationStore.observationInfos.filter({ (_, handler) -> Bool in | |
return handler(keyPath) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment