Last active
June 1, 2018 14:15
-
-
Save jakebromberg/2287006d53caf872aaf7e71ee1ee112b 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
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