LiveDataBus

全局共用的消息事件总线,可代替EventBus解决简单的数据传递功能

object LiveDataBus {
    private var bus: MutableMap> = mutableMapOf()


    private fun  with(key: String, type: Class): MutableLiveData {

        if (!bus.containsKey(key))
            bus[key] = MutableLiveData()

        return bus[key]!!
    }

    //发送消息
    fun  postNewValue(key: String, type: Class, value: Any) {
        this.with(key, type).postValue(value)
    }

    // 消费消息
    fun  receiveValue(
        key: String,
        type: Class,
        @NonNull owner: LifecycleOwner,
        @NonNull observer: Observer
    ) {
        this.with(key, type).observe(owner, observer)
    }
}

/*
 * 发送新值
 * LiveDataBus.postNewValue("data", String::class.java, "新值")
 */

/*
 * 注册和消费监听
 *LiveDataBus.receiveValue("data", String::class.java, this, object : Observer {
 *           override fun onChanged(t: Any?) {
 *               binding.showTv.text = t as String
 *           }
 *       })
 */

你可能感兴趣的:(LiveDataBus)