美文网首页
LiveDataBus

LiveDataBus

作者: 执念蓝枫 | 来源:发表于2021-03-26 15:15 被阅读0次

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

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]!!
    }

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

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

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

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

相关文章

  • 解密通信框架领域独秀LiveDataBus

    1、为什么要使用liveDataBus2、liveDataBus为什么会感知生命周期3、liveDataBus为什...

  • LiveData

    LiveDataBus实现原理#用法详解#LiveData扩展 LiveDataBus实现原理#用法详解#Live...

  • Android不使用反射,完成LiveDataBus

    LiveDataBus大家都很熟悉了,网上也有很多通过反射实现的LiveDataBus。但是通过反射实现的代码比较...

  • LiveDataBus

    LiveDataBus是基于LiveData实现的类似EventBus的消息通信框架,它是基于LiveData实现...

  • LiveDataBus

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

  • LiveDataBus 使用

    rxbus 优点 效率高,无内存泄露、UI和实时数据保持一致缺点: 依赖包 2.2M 比较大 EventBus ...

  • 进阶网址

    Android消息总线的演进之路:用LiveDataBus替代RxBus、EventBus Android 存储优...

  • Android LiveDatabus非黏性事件

    Android LiveDatabus非黏性事件 原文链接:https://blog.csdn.net/luoti...

  • JetPack之-LivedataBus

    背景 对于Android系统来说,消息传递是最基本的组件,每一个App内的不同页面,不同组件都在进行消息传递。消息...

  • LiveDataBus事件分发

    前言 很早之前就在项目中接触到了EventBus,觉得非常的方便,在任何地方都能注册事件,然后在任何地方都能发送,...

网友评论

      本文标题:LiveDataBus

      本文链接:https://www.haomeiwen.com/subject/mzijhltx.html