A safer KVO.
Example:
let kvObserver = KVObserver()
let observedObject = ObservedObject()
/* Start observing observedObject */
let observingId = kvObserver.observe(object: observedObject, keyPath: #keyPath(ObservedObject.observableProperty), kvoOptions: [.initial], dispatchType: .asyncOnMainQueueDirectInitial, handler: { [weak self] change in
/* Handle changes here */
})
/* End observing observedObject */
kvObserver.stopObserving(id: observingId)
/* Or, stop observing everything */
kvObserver.stopObservingEverything()
There are many dispatch types available, all of them with their subtle differences. Usually you’ll
need the default one: .asyncOnMainQueueDirectInitial
. This will dispatch the inital KVO
firing synchronously (if there is one, that is if the .inital
KVO option has been set), and further
KVO firing asynchronously on the main thread.
Don’t hesitate to read the code to learn about the other dispatch types! All of the types are documented. There even are dispatch types specifically for CoreData.
- Re-registration skipping
- Support for Swift 4
KeyPath
This project was originally created by François Lamboley while working at happn.