A lightweight Kotlin event bus with listener priorities, event cancellation and annotation-based subscription.
Maven Central
repositories { mavenCentral() }
dependencies {
implementation("org.noamm:eventbus:1.0.4")
}Define events by extending Event:
class PlayerJoinEvent(val name: String) : Event()
class DamageEvent : Event(cancelable = true)Create a bus and post events:
val bus = bus { setErrorHandler { throwable -> throw throwable } }
bus.post(PlayerJoinEvent("Notch"))
bus.post(DamageEvent())Mark methods with @SubscribeEvent and register the subscriber object:
val playerTracker = object {
@SubscribeEvent(priority = EventPriority.HIGH)
fun onJoin(event: PlayerJoinEvent) = println("${event.name} joined")
}
bus.subscribe(playerTracker)
bus.unsubscribe(playerTracker)Register inline listeners for an event class:
bus.register<DamageEvent> { event ->
event.isCanceled = true
}
bus.once<PlayerJoinEvent> { }register returns the EventListener
so you can unregister() it later.
Async listeners are suspending and read-only: they run on the bus dispatcher
after every other listener, so they cannot cancel the event or change the
result of post.
bus.registerAsync<DamageEvent> {
delay(100)
database.save(event)
}
@SubscribeEvent(async = true)
suspend fun onDamage(event: DamageEvent) { }
bus.postAsync(DamageEvent()) // fire-and-forget, returns a JobAsync work runs on Dispatchers.Default unless set with
bus { setDispatcher(Dispatchers.IO) }. Call bus.close() to cancel
pending async work.
- Listeners run from
HIGHESTtoLOWESTpriority. - Canceling an event skips listeners not registered with
receiveCancelled = true. - Exceptions thrown by listeners are routed to the error handler configured on
the
EventBusBuilder(rethrown by default).