Last active
June 8, 2018 08:08
-
-
Save xxKRASHxx/494b04f3d850ee0d0b53f5b6259f90f6 to your computer and use it in GitHub Desktop.
Notification mechanism
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
public class Token { | |
public typealias DisposeAction = () -> Void | |
private let action: DisposeAction | |
private var isDisposed: Bool = false | |
public init(action: @escaping DisposeAction) { self.action = action } | |
private func innerDispose() { | |
guard !isDisposed else { return } | |
isDisposed = true | |
action() | |
} | |
public func dispose() { innerDispose() } | |
deinit { innerDispose() } | |
} | |
public class Pipe<Element> { | |
public let signal = Signal<Element>() | |
public func dispatch(_ value: Element) { | |
signal.dispatch(value) | |
} | |
public init() {} | |
} | |
public class Signal<Element> { | |
public typealias Callback = (Element) -> Void | |
private var callbacks = [:] as [Int: Callback] | |
private var nextID = 0 | |
fileprivate func dispatch(_ value: Element) { | |
callbacks.forEach { $1(value) } | |
} | |
public func onUpdate(_ callback: @escaping Callback) -> Token { | |
let id = nextID | |
nextID += 1 | |
callbacks[id] = callback | |
return Token { [weak self] in self?.callbacks[id] = nil } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of usage:
will print: