Skip to content

Instantly share code, notes, and snippets.

@amin3536
Forked from DaleLaw/EventBus.kt
Created July 9, 2020 06:43
Show Gist options
  • Save amin3536/0d50c77d25d847ccb1f97f2ce5e11b3b to your computer and use it in GitHub Desktop.
Save amin3536/0d50c77d25d847ccb1f97f2ce5e11b3b to your computer and use it in GitHub Desktop.
Implement EventBus with Kotlin coroutine
object EventBus {
val bus: BroadcastChannel<Any> = BroadcastChannel()
fun send(o: Any) {
launch {
bus.send(o)
}
}
inline fun <reified T> asChannel(): ReceiveChannel<T> {
return bus.openSubscription().filter { it is T }.map { it as T }
}
}
// To post an event:
EventBus.send(SomeEvent())
// To subscribe to an event:
var subscription = EventBus.asChannel<SomeEvent>()
launch(UI) {
subscription.consumeEach { event ->
// Handles the event...
}
}
// To cancel a subscriber:
subscription.cancel()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment