Last active
November 2, 2023 15:25
-
-
Save DaleLaw/17567f19dc001ec4677f194517a8a3f1 to your computer and use it in GitHub Desktop.
Implement EventBus with Kotlin coroutine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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