SwiftBus - A lightweight Event Bus library written in Swift
I've created a simple and lightweight EventBus library. It is written in Swift and powered by Combine:
The main feature of the SwiftBus is ability to send and receive custom events:
import SwiftBus
import Combine
// 1. Define custom event
struct RebelsActivityDetectedEvent: EventRepresentable {
let planet: String
let distanceInParsecs: Int
}
// 2. Create EventBus
let eventBus: EventTransmittable = EventBus()
var subscriptions: Set<AnyCancellable> = []
// 3. Add event handlers and store the reference to a subscription
eventBus.onReceive(RebelsActivityDetectedEvent.self) { event in
print("Detected rebels \(event.distanceInParsecs) parsecs from us on \(event.planet)")
}
.store(in: &subscriptions)
// 4. Send event
let event = RebelsActivityDetectedEvent(planet: "Hoth", distanceInParsecs: 12)
eventBus.send(event)
It can also operate just on named events:
import SwiftBus
import Combine
// 1. Create EventBus
let eventBus: EventTransmittable = EventBus()
var subscriptions: Set<AnyCancellable> = []
// 2. Add handler for named event with params
eventBus.onReceive("RebelsActivityDetected") { params in
print("Detected rebels \(params["distanceInParsecs"]) parsecs from us on \(params["planet"])")
}
.store(in: &subscriptions)
// 3. Send named event with params
eventBus.send("RebelsActivityDetected", params: ["planet": "Hoth", "distanceInParsecs": 12])
The SwiftBus should be a nice replacement for good old NotificationCenter :)