Skip to content

Instantly share code, notes, and snippets.

@prasad79
Created March 7, 2019 16:35
Show Gist options
  • Save prasad79/ec121b01e66151aec1e370bfee389ea4 to your computer and use it in GitHub Desktop.
Save prasad79/ec121b01e66151aec1e370bfee389ea4 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