Skip to content

Instantly share code, notes, and snippets.

@ronjunevaldoz
Last active June 22, 2021 06:25
Show Gist options
  • Save ronjunevaldoz/cd69cb040ffa94d79d04998a116abf0d to your computer and use it in GitHub Desktop.
Save ronjunevaldoz/cd69cb040ffa94d79d04998a116abf0d to your computer and use it in GitHub Desktop.
object EventBus {
@OptIn(ExperimentalCoroutinesApi::class)
val bus: BroadcastChannel<Any> = ConflatedBroadcastChannel(2) // receive only most recent data
@ExperimentalCoroutinesApi
fun send(o: Any) = runBlocking {
launch {
bus.send(o)
}
}
@ExperimentalCoroutinesApi
inline fun <reified T> asFlow(): Flow<T> {
return bus.openSubscription().filter { it is T }.map { it as T }.consumeAsFlow()
}
inline fun <reified T> asChannel(): ReceiveChannel<T> {
return bus.openSubscription().filter { it is T }.map { it as T }
}
}
// updated as of 6/22/2021
@OptIn(ExperimentalCoroutinesApi::class)
object GameEventManager {
private val _events = MutableSharedFlow<Any>() // no buffer, rendezvous with subscribers
val events: SharedFlow<Any> get() = _events // expose as a plain flow
inline fun <reified T> asChannel(crossinline action: (value: T) -> Unit) {
KtxAsync.launch {
events.filterIsInstance<T>().collect { event-> action.invoke(event) }
}
}
fun send(e: Any) {
KtxAsync.launch {
produceEvent(e)
}
}
private suspend fun produceEvent(event: Any) {
_events.emit(event) // suspends until all subscribers receive it
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment