Skip to content

Instantly share code, notes, and snippets.

@DevHossamHassan
Created January 12, 2020 19:26
Show Gist options
  • Save DevHossamHassan/2eabb81d2b73f4e489cecc9c0e97e64c to your computer and use it in GitHub Desktop.
Save DevHossamHassan/2eabb81d2b73f4e489cecc9c0e97e64c 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