Last active
January 28, 2019 11:57
-
-
Save corysullivan/bdfcefa902b4814868cbe786d30d4369 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
| /// A thread safe class for managing an array of objects of a given type. The sequence holds | |
| /// weak references to the contained objects, allowing them to be deallocated and | |
| /// removed automatically. Order is maintained within the sequence. | |
| class Listener<T> { | |
| private let listeners: NSHashTable<AnyObject> = NSHashTable.weakObjects() | |
| private let lockingQueue = DispatchQueue(label: "com.livelike.listenerSynchronizer", attributes: .concurrent) | |
| func addListener(_ listener: T) { | |
| lockingQueue.async(flags: .barrier) { [weak self] in | |
| self?.listeners.add(listener as AnyObject) | |
| } | |
| } | |
| func removeListener(_ listener: T) { | |
| lockingQueue.async(flags: .barrier) { [weak self] in | |
| self?.listeners.remove(listener as AnyObject) | |
| } | |
| } | |
| func removeAll() { | |
| lockingQueue.async(flags: .barrier) { [weak self] in | |
| self?.listeners.removeAllObjects() | |
| } | |
| } | |
| func publish(_ invocation: (T) -> Void) { | |
| lockingQueue.sync { [weak self] in | |
| guard let self = self else { return } | |
| for listner in self.listeners.allObjects { | |
| invocation(listner as! T) | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment