Created
November 15, 2019 14:25
-
-
Save KryptKode/82abd2e05bc23e3a7398bced2286f2e1 to your computer and use it in GitHub Desktop.
Kotlin coroutine-based event bus
This file contains 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
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