Skip to content

Instantly share code, notes, and snippets.

@DaleLaw
Last active November 2, 2023 15:25
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save DaleLaw/17567f19dc001ec4677f194517a8a3f1 to your computer and use it in GitHub Desktop.
Save DaleLaw/17567f19dc001ec4677f194517a8a3f1 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