Skip to content

Instantly share code, notes, and snippets.

@KryptKode
Created November 15, 2019 14:25
Show Gist options
  • Save KryptKode/82abd2e05bc23e3a7398bced2286f2e1 to your computer and use it in GitHub Desktop.
Save KryptKode/82abd2e05bc23e3a7398bced2286f2e1 to your computer and use it in GitHub Desktop.
Kotlin coroutine-based event bus
import kotlinx.coroutines.experimental.DefaultDispatcher
import kotlinx.coroutines.experimental.channels.BroadcastChannel
import kotlinx.coroutines.experimental.channels.ReceiveChannel
import kotlinx.coroutines.experimental.channels.filter
import kotlinx.coroutines.experimental.channels.map
import kotlinx.coroutines.experimental.launch
import kotlin.coroutines.experimental.CoroutineContext
class EventBus {
private val channel = BroadcastChannel<Any>(1)
fun send(event: Any, context: CoroutineContext = DefaultDispatcher) {
launch(context) {
channel.send(event)
}
}
fun subscribe(): ReceiveChannel<Any> =
channel.openSubscription()
inline fun <reified T> subscribeToEvent() =
subscribe().filter { it is T }.map { it as T }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment