-
-
Save KryptKode/f6d274c13ac95b9413573738b771c4ca to your computer and use it in GitHub Desktop.
EventBus by Kotlin coroutine
This file contains 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
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