Created
April 8, 2018 08:00
-
-
Save laevandus/5c48827b3a9c43c898a7dd5811676c0c to your computer and use it in GitHub Desktop.
Class adding a support for observing a property.
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 Observable<T> { | |
init(_ value: T) { | |
self.value = value | |
} | |
var value: T { | |
didSet { | |
changeHandlers.forEach({ $0.handler(value) }) | |
} | |
} | |
typealias ChangeHandler = ((T) -> Void) | |
private var changeHandlers: [(identifier: Int, handler: ChangeHandler)] = [] | |
/** | |
Adds observer to the value. | |
- parameter initial: The handler is run immediately with initial value. | |
- parameter handler: The handler to execute when value changes. | |
- returns: Identifier of the observer. | |
*/ | |
@discardableResult func observe(initial: Bool = false, handler: @escaping ChangeHandler) -> Int { | |
let identifier = UUID().uuidString.hashValue | |
changeHandlers.append((identifier, handler)) | |
guard initial else { return identifier } | |
handler(value) | |
return identifier | |
} | |
/** | |
Removes observer to the value. | |
- parameter observer: The observer to remove. | |
*/ | |
func removeObserver(_ observer: Int) { | |
changeHandlers = changeHandlers.filter({ $0.identifier != observer }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment