Skip to content

Instantly share code, notes, and snippets.

@oleksii-demedetskyi
Created June 16, 2017 11:01
Show Gist options
  • Save oleksii-demedetskyi/196c8b33f12878d807ccfb7ac37ca6e0 to your computer and use it in GitHub Desktop.
Save oleksii-demedetskyi/196c8b33f12878d807ccfb7ac37ca6e0 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import Cocoa
class Observation<T>: Hashable {
var hashValue: Int {
return ObjectIdentifier(self).hashValue
}
static func ==(lhs: Observation<T>, rhs: Observation<T>) -> Bool {
return lhs === rhs
}
let observer: (T) -> ()
init(observer: @escaping (T) -> ()) {
self.observer = observer
}
}
class Observable<T> {
var value: T {
didSet {
for observation in observations {
observation.observer(value)
}
}
}
private var observations: Set<Observation<T>> = []
init(value: T) {
self.value = value
}
func observe<U>(_ keyPath: KeyPath<T, U>,
callback: @escaping (U) -> ()) -> (() -> ()) {
observations.insert(Observation<T> {
callback($0[keyPath: keyPath])
})
return {}
}
}
struct User {
let name: String
let age: Int
}
let observableUser = Observable(value: User(name: "Jonh", age: 35))
let nameObservation = observableUser.observe(\.name) { name in
print("New name:", name)
}
let ageObservation = observableUser.observe(\.age) { age in
print("New age:", age)
}
observableUser.value = User(name: "Dow", age: 40)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment