Created
March 7, 2019 16:35
-
-
Save prasad79/ec121b01e66151aec1e370bfee389ea4 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