SwiftyEventBus is a publish/subscribe event bus for iOS and Swift.
- simplifies the communication between components
- make your code simple and elegant
- type safe
- more advance feature: safety event, sticky event, etc...
In addition, if you want to read document, please click here.
SwiftyEventBus
is very easy to use, you just need two steps:
You can register in anywhere with any type, it will always observe until the EventSubscription
object been released.
class DemoViewController: UIViewController {
var ob: EventSubscription<String>!
override func viewDidLoad() {
super.viewDidLoad()
ob = EventBus.`default`.register { (x: String) in
print(x)
}
}
}
Finally, you just need to post any type that implement EventPresentable
.
EventBus.default.post("Foo")
Sometime, you maybe post a message that no one obseving, this is unsafety behaviour, then you can use this:
EventBus.default.safePost("Foo")
If there is no observer subscribe this kind of message, EventBus.default.safePost("Foo")
will raise EventBusPostError.useless
Exception, you can catch it and handle this.
/// handle EventBusPostError excetion
do {
try EventBus.default.safePost("foo")
} catch {
// do something
}
if you project using RxSwift
, maybe you need this to bridge SwiftyEventBus
to Rx
.
pod 'SwiftyEventBus/Rx'
after that, you can use SwiftyEventBus
in RxSwift
world.π
var bag: DisposeBag? = DisposeBag()
EventBus.default.rx.register(String.self)
.subscribe(onNext: { (x) in
print(x) /// "foo"
})
.disposed(by: bag!)
EventBus.default.post("foo")
To run the example project, clone the repo, and run pod install
from the Example directory first.
SwiftyEventBus is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'SwiftyEventBus'
SwiftyEventBus is also available on Carthage
, please add this to Cartfile
:
github "Maru-zhang/SwiftyEventBus"
Maru-zhang, maru-zhang@foxmail.com
SwiftyEventBus is available under the MIT license. See the LICENSE file for more info.