Created
January 31, 2019 13:47
-
-
Save dimix/ae724142f74bc0c03158ed06e7a3bede to your computer and use it in GitHub Desktop.
PROVA
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
class Disposable { | |
typealias ClosureType = () -> Void | |
let closure: ClosureType | |
init(_ closure: @escaping ClosureType) | |
{ | |
self.closure = closure | |
} | |
deinit | |
{ | |
closure() | |
} | |
} | |
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 | |
guard let newValue = change.newValue else { return } | |
onChange(newValue) | |
} | |
return Disposable { observation.invalidate() } | |
} | |
} | |
// How to use | |
@objc dynamic var toObserve: String = "" | |
let disposable = observe(\.toObserve, onChange: { value in | |
debugPrint(“changed: \(value)") | |
}) | |
toObserve = “Set new value“ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment