TPEventBus
TPEventBus 是受 EventBus 和 QTEventBus 启发的 iOS 发布/订阅事件总线。
图片来源:EventBus
三步 EventBus
-
定义事件
class TPCountEvent: NSObject, TPEvent { var count: Int init(count: Int) { self.count = count } }
-
准备订阅者
订阅者实现事件处理方法,该方法将在接收到事件时被调用。
@objc func onCountEvent(event: TPCountEvent, object: Any?) { // do something }
注册和注销您的订阅者。
注意:当订阅者被释放时,它将自动注销。
// Register TPEventBus<TPCountEvent>.shared.register(eventType: TPCountEvent.self, subscriber: self, selector: #selector(onCountEvent(event:object:))) // Unregister TPEventBus<TPCountEvent>.shared.unregister(eventType: TPCountEvent.self, subscriber: self)
-
发布事件
let event = TPCountEvent.init(count: count) TPEventBus.shared.post(event: event, object: self)
便利性
TPEventBus<TPCountEvent>.shared.subscribe(eventType: TPCountEvent.self).onQueue(OperationQueue.main).onEvent { [weak self] (event, object) in
guard let self = self else {
return
}
// do something
}.disposed(by: self.tp_eventTokenBag)
示例
要运行示例项目,请克隆仓库,然后首先从 Example 目录运行 pod install
命令。
安装
TPEventBus 可以通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile
pod 'TPEventBus'
作者
tpphha, [email protected]
许可证
TPEventBus 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。