Skip to content

Instantly share code, notes, and snippets.

@tkrajacic
Created April 3, 2019 04:33
Show Gist options
  • Save tkrajacic/24515bae65f09c6eb8c915af1bd357c5 to your computer and use it in GitHub Desktop.
Save tkrajacic/24515bae65f09c6eb8c915af1bd357c5 to your computer and use it in GitHub Desktop.
// From objc.io's app architecture book
// https://github.com/objcio/app-architecture
import Foundation
extension NSObjectProtocol where Self: NSObject {
func observe<Value>(_ keyPath: KeyPath<Self, Value>, onChange: @escaping (Value) -> ()) -> Disposable {
let observation = observe(keyPath, options: [.initial, .new]) { _, change in
// See: https://bugs.swift.org/browse/SR-6066
let newValue = change.newValue ?? (nil as Any? as! Value)
onChange(newValue)
}
return Disposable { observation.invalidate() }
}
func bind<Value, Target>(_ sourceKeyPath: KeyPath<Self, Value>, to target: Target, at targetKeyPath: ReferenceWritableKeyPath<Target, Value>) -> Disposable {
return observe(sourceKeyPath) { target[keyPath: targetKeyPath] = $0 }
}
}
final class Disposable {
let dispose: () -> ()
init(_ dispose: @escaping () -> ()) {
self.dispose = dispose
}
deinit {
dispose()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment