Skip to content

Instantly share code, notes, and snippets.

@hoc081098
Created October 30, 2023 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoc081098/e468a57ce23b61f18d53808a3e8e1b95 to your computer and use it in GitHub Desktop.
Save hoc081098/e468a57ce23b61f18d53808a3e8e1b95 to your computer and use it in GitHub Desktop.
public class ChannelsEventBus {
private val _channels = hashMapOf<KClass<*>, Channel<Any>>()
private fun createChannel(key: KClass<*>) = synchronized(this) { _channels.getOrPut(key) { Channel(Channel.UNLIMITED) } }
public fun send(event: Any): Unit = createChannel(event::class).trySend(event).let { }
@Suppress("UNCHECKED_CAST")
public fun <T : Any> receiveAsFlow(type: KClass<T>): Flow<T> = flow {
createChannel(type)
.receiveAsFlow()
.map { it as T }
.let { emitAll(it) }
}
public inline fun <reified T: Any> receiveAsFlow(): Flow<T> = receiveAsFlow(T::class)
}
private data class Event1(val value: Int)
private data class Event2(val value: String)
public fun main(): Unit = runBlocking {
val bus = ChannelsEventBus()
bus.send(Event1(1))
bus.send(Event2("X"))
launch {
bus.receiveAsFlow<Event1>().collect { event1: Event1 ->
}
}
launch {
bus.receiveAsFlow<Event2>().collect { event2: Event2 ->
}
}
}
@hoc081098
Copy link
Author

🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment