Skip to content

Instantly share code, notes, and snippets.

@corysullivan
Last active January 28, 2019 11:57
Show Gist options
  • Select an option

  • Save corysullivan/bdfcefa902b4814868cbe786d30d4369 to your computer and use it in GitHub Desktop.

Select an option

Save corysullivan/bdfcefa902b4814868cbe786d30d4369 to your computer and use it in GitHub Desktop.
/// 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