支持 生命 周期 感知 支持 自 动清除 空 闲事件
/**
* 订阅事件 (EventFlow)或 状 态(StateFlow)
*
* - 对于 [EventFlow],进入 [minState] 开始订阅,脱 离 [minState] 取消 订阅
* - 对于 [StateFlow],满足 [minState] 时立刻 消 费,不足 [minState] 时缓存 最近 的 事件 待 再 次 进入时消费
*
*/
fun <T> Flow<T>.observe(owner: LifecycleOwner, minState: Lifecycle.State = Lifecycle.State.STARTED, action: suspend (T) -> Unit)
/**
* 订阅事件 ,满足 [minState] 时立刻 消 费,不足 [minState] 时缓存 最近 的 事件 待 再 次 进入时消费
*
* 示 例 :在 A页观察流,然 后 进入B页发送了 事件 ,回 到 A页消费事件
*/
fun <T> Flow<T>.observeLatest(owner: LifecycleOwner, minState: Lifecycle.State = Lifecycle.State.STARTED, action: suspend (T) -> Unit)
/**
* 进入 [minState] 开始订阅,脱 离 [minState] 取消 订阅
* */
fun <T> Flow<T>.observeRepeat(owner: LifecycleOwner, minState: Lifecycle.State = Lifecycle.State.STARTED, action: suspend (T) -> Unit)
data class FooEvent(val value: String)
data class BarEvent(val value: String)
object Global {
val eventFoo = EventFlow<FooEvent>()
val stateCount = MutableStateFlow(0)
}
Global.stateCount.observe(this) {
binding.state.text = "count = $it"
}
Global.eventFoo.observeLatest(this) {
log("Global => $it")
}
EventBus.observe<BarEvent>(this) {
log("EventBus => $it")
}
binding.fooEvent.setOnClickListener {
Global.eventFoo.tryEmit(FooEvent("clicked in main"))
}
binding.barEvent.setOnClickListener {
EventBus.emit(BarEvent("clicked in main"))
}
repositories {
maven { url "https://gitee.com/ezy/repo/raw/cosmo/"}
}
dependencies {
implementation "me.reezy.cosmo:flowbus:0.9.0"
}
The Component is open-sourced software licensed under the Apache license.