Skip to content

Instantly share code, notes, and snippets.

@KryptKode
Forked from takahirom/EventBus.kt
Created November 15, 2019 14:25
Show Gist options
  • Save KryptKode/f6d274c13ac95b9413573738b771c4ca to your computer and use it in GitHub Desktop.
Save KryptKode/f6d274c13ac95b9413573738b771c4ca 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 }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment