经过高强度测试,(基本上)莫得问题
需要导入的kotlin协程库:
//lifecycleScope(这里是用kotlin写的)
api("androidx.activity:activity-ktx:1.2.2")
api("androidx.fragment:fragment-ktx:1.3.6")
api("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0")
如何使用:
第一步:注册事件
???????Bus.with<Int>("your_key").register(this) {
binding.tvNum.text = "$it"
}
?第二步:发送事件
Bus.with<Int>("your_key").post(num)
代码?
object Bus {
private const val TAG = "BUS"
private val busMap = mutableMapOf<String, EventBus<*>>()
/**
* Get EventBus
* @return returned object cannot be saved as a variable
*/
@Synchronized
fun <T> with(key: String): EventBus<T> {
var eventBus = busMap[key]
if (eventBus == null) {
eventBus = EventBus<T>(key)
busMap[key] = eventBus
}
return eventBus as EventBus<T>
}
class EventBus<T>(private val key: String) : LifecycleObserver {
private val _events = MutableSharedFlow<T>() // private mutable shared flow
val events = _events.asSharedFlow() // publicly exposed as read-only shared flow
/**
* need main thread execute
*/
fun register(lifecycleOwner: LifecycleOwner, action: (t: T) -> Unit) {
lifecycleOwner.lifecycle.addObserver(this)
lifecycleOwner.lifecycleScope.launch {
events.collect {
try {
action(it)
} catch (e: Exception) {
Log.e(TAG, "KEY:%s---ERROR:%s".format(key, e.toString()))
}
}
}
}
/**
* send value
*/
suspend fun post(event: T) {
_events.emit(event)
}
/**
* When subscriptionCount less than 0,remove event object in map
*/
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
val subscriptCount = _events.subscriptionCount.value
if (subscriptCount <= 0)
busMap.remove(key)
}
}
}
|