Created
April 9, 2019 13:53
-
-
Save jeffery812/c61572a52fd9e70b0d8380356e690465 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Observable<Value> { | |
private var value: Value | |
private var observations = [UUID : (Value) -> Void]() | |
init(value: Value) { | |
self.value = value | |
} | |
func update(with value: Value) { | |
self.value = value | |
for observation in observations.values { | |
observation(value) | |
} | |
} | |
func addObserver<O: AnyObject>(_ observer: O, | |
using closure: @escaping (O, Value) -> Void) { | |
let id = UUID() | |
observations[id] = { [weak self, weak observer] value in | |
// If the observer has been deallocated, we can safely remove | |
// the observation. | |
guard let observer = observer else { | |
self?.observations[id] = nil | |
return | |
} | |
closure(observer, value) | |
} | |
// Directly call the observation closure with the | |
// current value. | |
closure(observer, value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment