Skip to content

Instantly share code, notes, and snippets.

@dimix
Created January 31, 2019 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimix/ae724142f74bc0c03158ed06e7a3bede to your computer and use it in GitHub Desktop.
Save dimix/ae724142f74bc0c03158ed06e7a3bede to your computer and use it in GitHub Desktop.
PROVA
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