Created
October 30, 2023 18:37
-
-
Save hoc081098/e468a57ce23b61f18d53808a3e8e1b95 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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 -> | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
🙏