全局共用的消息事件總線获讳,可代替EventBus解決簡單的數(shù)據(jù)傳遞功能
object LiveDataBus {
private var bus: MutableMap<String, MutableLiveData<Any>> = mutableMapOf()
private fun <T> with(key: String, type: Class<T>): MutableLiveData<Any> {
if (!bus.containsKey(key))
bus[key] = MutableLiveData()
return bus[key]!!
}
//發(fā)送消息
fun <T> postNewValue(key: String, type: Class<T>, value: Any) {
this.with(key, type).postValue(value)
}
// 消費(fèi)消息
fun <T> receiveValue(
key: String,
type: Class<T>,
@NonNull owner: LifecycleOwner,
@NonNull observer: Observer<in Any>
) {
this.with(key, type).observe(owner, observer)
}
}
/*
* 發(fā)送新值
* LiveDataBus.postNewValue("data", String::class.java, "新值")
*/
/*
* 注冊和消費(fèi)監(jiān)聽
*LiveDataBus.receiveValue("data", String::class.java, this, object : Observer<Any> {
* override fun onChanged(t: Any?) {
* binding.showTv.text = t as String
* }
* })
*/