TPEventBus
TPEventBus is a publish/subscribe event bus for iOS, inspired by EventBus and QTEventBus.
Source of the picture: EventBus
EventBus in 3 steps
-
Define events:
class TPCountEvent: NSObject, TPEvent { var count: Int init(count: Int) { self.count = count } }
-
Prepare subscribers:
Subscribers implement event handling methods that will be called when an event is received.
@objc func onCountEvent(event: TPCountEvent, object: Any?) { // do something }
Register and unregister your subscriber.
Notice: When the subscriber is released, it will be automatically unregistered.
// 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)
-
Post events:
let event = TPCountEvent.init(count: count) TPEventBus.shared.post(event: event, object: self)
Convenience
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
To run the example project, clone the repo, and run pod install
from the Example directory first.
Installation
TPEventBus is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'TPEventBus'
Author
tpphha, [email protected]
License
TPEventBus is available under the MIT license. See the LICENSE file for more info.