Created
April 3, 2019 04:33
-
-
Save tkrajacic/24515bae65f09c6eb8c915af1bd357c5 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
// 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