1 of 5

Getting Started

Install kotlin-events, define events and listeners, and emit your first event.

Installation

Add the dependency to your build.gradle.kts:

kotlin
dependencies {
    implementation("com.cristianllanos:events:1.0.0")
}

If your listeners need to call suspend functions, use the coroutines module instead — it includes events-core as a transitive dependency:

kotlin
dependencies {
    implementation("com.cristianllanos:events-coroutines:1.0.0")
}

Both modules pull in kotlin-container for dependency injection.

Events and listeners

Events are data classes that implement Event. Listeners implement Listener<T> with a typed handle method:

kotlin
data class UserCreated(val name: String) : Event

class SendWelcomeEmail(private val mailer: Mailer) : Listener<UserCreated> {
    override fun handle(event: UserCreated) {
        mailer.send("Welcome, ${event.name}!")
    }
}

Listeners are resolved from the DI container on each emit, so their constructor dependencies are auto-injected. No manual wiring needed.

Wiring up

Create an EventBus, subscribe listeners to event types, and emit:

kotlin
val bus = EventBus(container)
bus.subscribe<UserCreated, SendWelcomeEmail>()
bus.emit(UserCreated("Alice"))

The EventBus factory takes a Resolver (any kotlin-container Container implements this). When you emit an event, the bus resolves each registered listener class from the container and calls handle.

Service provider

EventServiceProvider registers EventBus, Emitter, and Subscriber as singletons in a container:

kotlin
val container = Container()
EventServiceProvider().register(container)

val bus = container.resolve<EventBus>()
bus.subscribe<UserCreated, SendWelcomeEmail>()
bus.emit(UserCreated("Alice"))

This is the recommended setup — the bus is shared across your application, and any component resolved from the container can receive Emitter or Subscriber through constructor injection.

Next steps

Now that you have a working event bus, learn about lambda handlers, one-shots, and the registration DSL.