Skip to content

Kotlin usage

λ edited this page Jul 5, 2022 · 2 revisions

Kawa was designed to be used within Kotlin projects. So the kotlin-listener-dsl artifact provides a small yet complete DSL to use for creating listeners. Here is how to make it work.

Instancing an event bus

There isn't any simpler than instancing an event bus. An optimized Kawa implementation example is available as the optimized-bus artifact, which is production-ready. After importing it, you can use it as such:

import wtf.mizu.kawa.OptimizedBus

fun main() {
    val bus = OptimizedBus()
}

Creating, registering and removing listeners

To create a listener, you can use the listener DSL function as such:

import wtf.mizu.kawa.dsl.listener

fun main() {
    val listener = listener { // 'this' is a KListener, basically just a Kotlin boxing of the original api.Listener class.
        on<String> { // 'it' is of the provided type, here it's a String, but it can be anything you want it to be.
            println(it)
            // This example will only print out the Strings that will be sent through the event bus(es) that this Listener gets registered to.
        }
    }
}

After creating a listener, registering it to an event bus is as easy as follows:

import wtf.mizu.kawa.OptimizedBus
import wtf.mizu.kawa.dsl.listener

fun main() {
    val bus = OptimizedBus()

    val listener = listener { 
        on<String> {
            println(it)
        }
    }

    bus.addListener(listener)
}

If however you would like your listener to be removed from this bus, you can always use the Bus#removeListener(Listener) method!

Publishing to the event bus

Now that you've got yourself an event bus along with a listener, you can publish events to it. The hardest part to understand is that a listener only gets its definition called when an object matching the listener's type is published to the bus. Yeah. Here's how to do it:

import wtf.mizu.kawa.OptimizedBus
import wtf.mizu.kawa.dsl.listener

fun main() {
    val bus = OptimizedBus()

    val listener = listener { 
        on<String> {
            println(it)
        }
    }

    bus.addListener(listener)

    val event = "foobar123"
    bus.publish(event)
}