Type-safe coroutine-based event bus for Kotlin with Flow integration
implementation com.philiprehberger:event-busType-safe coroutine-based event bus for Kotlin with Flow integration.
implementation("com.philiprehberger:event-bus:0.2.0")
<dependency>
<groupId>com.philiprehberger</groupId>
<artifactId>event-bus</artifactId>
<version>0.2.0</version>
</dependency>
import com.philiprehberger.eventbus.*
data class UserCreated(val name: String)
data class OrderPlaced(val orderId: Int, val total: Double)
val bus = EventBus()
// Subscribe to specific event types
bus.on<UserCreated>(scope) { event ->
println("User created: ${event.name}")
}
// Emit events
bus.emit(UserCreated("Alice"))
bus.emit(OrderPlaced(1, 99.99)) // Not received by UserCreated subscriber
bus.flow<OrderPlaced>()
.filter { it.total > 100.0 }
.collect { order ->
processLargeOrder(order)
}
// Subscription is tied to a CoroutineScope
val job = bus.on<UserCreated>(scope) { handle(it) }
// Cancel manually
job.cancel()
// Or automatically when the scope is cancelled
scope.cancel()
// Automatically unsubscribes after the first matching event
bus.once<UserCreated>(scope) { event ->
println("First user: ${event.name}")
}
val count = bus.subscriberCount()
println("Active subscribers: $count")
| Class / Function | Description |
|---|---|
EventBus | Main event bus class backed by MutableSharedFlow |
EventBus.on<T>() | Subscribe to events of type T within a CoroutineScope |
EventBus.emit() | Emit an event to all matching subscribers |
EventBus.flow<T>() | Get a Flow of events filtered to type T |
EventBus.once<T>() | Subscribe to only the first matching event |
EventBus.subscriberCount() | Get the number of active subscribers |
./gradlew test # Run tests
./gradlew check # Run all checks
./gradlew build # Build JAR
If you find this project useful: