Skip to content

Instantly share code, notes, and snippets.

@jakebromberg
Last active June 1, 2018 14:15
Show Gist options
  • Save jakebromberg/2287006d53caf872aaf7e71ee1ee112b to your computer and use it in GitHub Desktop.
Save jakebromberg/2287006d53caf872aaf7e71ee1ee112b to your computer and use it in GitHub Desktop.
final class WeakBox<A: AnyObject> {
weak var unbox: A?
init(_ value: A) {
unbox = value
}
}
typealias Callback<T> = (T) -> ()
final class Observation<T> {
let callback: Callback<T>
typealias Deinitializer = (Observation) -> ()
let deinitializer: Deinitializer?
init(_ callback: @escaping Callback<T>, deinitializer: Deinitializer? = nil) {
self.callback = callback
self.deinitializer = deinitializer
}
deinit {
self.deinitializer?(self)
}
}
final class Observable<T> {
private var observations: [WeakBox<Observation<T>>] = []
func observe(callback: @escaping Callback<T>) -> Observation<T> {
let observation = Observation(callback, deinitializer: self.remove(observation:))
self.observations.append(WeakBox(observation))
return observation
}
func update(with value: T) {
for observation in observations {
observation.unbox?.callback(value)
}
}
func remove(observation: Observation<T>) {
guard let index = self.observations.index(where: { return observation === $0 }) else {
return
}
self.observations.remove(at: index)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment