Last active
June 8, 2024 14:09
-
-
Save takahirom/f2dbcc3053adfd87ac7e321d95a23021 to your computer and use it in GitHub Desktop.
EventBus by Kotlin coroutine
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
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
this is for kotlin version ="1.4.20"
@ExperimentalCoroutinesApi
object CoroutinesEvent {
}