Skip to content

Instantly share code, notes, and snippets.

@takahirom
Last active June 9, 2022 10:21
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save takahirom/f2dbcc3053adfd87ac7e321d95a23021 to your computer and use it in GitHub Desktop.
Save takahirom/f2dbcc3053adfd87ac7e321d95a23021 to your computer and use it in GitHub Desktop.
EventBus by Kotlin coroutine
import kotlinx.coroutines.experimental.channels.BroadcastChannel
import kotlinx.coroutines.experimental.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.experimental.channels.ReceiveChannel
import kotlinx.coroutines.experimental.channels.filter
import kotlinx.coroutines.experimental.channels.map
import kotlinx.coroutines.experimental.launch
import javax.inject.Inject
import javax.inject.Singleton
/**
* You can use like this.
* val channel = EventBus().asChannel<ItemChangeAction>()
* launch (UI){
* for(action in channel){
* // You can use item
* action.item
* }
* }
*/
@Singleton
class EventBus @Inject constructor() {
val bus: BroadcastChannel<Any> = ConflatedBroadcastChannel<Any>()
fun send(o: Any) {
launch {
bus.send(o)
}
}
inline fun <reified T> asChannel(): ReceiveChannel<T> {
return bus.openSubscription().filter { it is T }.map { it as T }
}
}
@mbarkiMohamed
Copy link

mbarkiMohamed commented Jan 7, 2021

this is for kotlin version ="1.4.20"

@ExperimentalCoroutinesApi

object CoroutinesEvent {

private val observerChanner = BroadcastChannel<Any>(Channel.BUFFERED)

suspend fun publish(Response: Any) {

    observerChanner.send(Response)

}

fun <Any> listen(eventType: Class<Any>): ReceiveChannel<Any> =
    observerChanner.openSubscription().filter { it is kotlin.Any }.map { it as Any }

}

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