Last active
October 19, 2016 06:32
-
-
Save KelvinJin/4e18fbc156b8ba0abd1491d731538db9 to your computer and use it in GitHub Desktop.
A class written in Swift that simplifies how notification works in iOS.
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
class SwiftyBus { | |
private static let notificationQueue = DispatchQueue(label: "com.swiftybus.notification") | |
struct Observer { | |
let callback: Any | |
let queue: DispatchQueue | |
} | |
static let shared = SwiftyBus() | |
private var pools: [String: [String: Observer]] = [:] | |
@discardableResult | |
func register<T>(indexKey: String = UUID().uuidString, queue: DispatchQueue = notificationQueue, observer: @escaping (T) -> Void) -> String { | |
let key = "\(type(of: T.self))" | |
var cPool = pools[key] ?? [:] | |
cPool[indexKey] = Observer(callback: observer, queue: queue) | |
pools[key] = cPool | |
return indexKey | |
} | |
@discardableResult | |
func unregister<T>(indexKey: String) -> ((T) -> Void)? { | |
let key = "\(type(of: T.self))" | |
guard var cPool = pools[key] else { return nil } | |
let observer = cPool.removeValue(forKey: indexKey) | |
pools[key] = cPool | |
return observer?.callback as? (T) -> Void | |
} | |
func notify<T>(object: T) { | |
let key = "\(type(of: T.self))" | |
guard let cPool = pools[key] else { return } | |
cPool.values.forEach { item in | |
guard let observer = item.callback as? (T) -> Void else { return } | |
item.queue.async { | |
observer(object) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample Usage