转载

使用官方的LiveData 实现消息总线 LiveDataBus


class LiveDataBus private constructor() {
    private val bus: MutableMap<String, BusMutableLiveData<Any>>

    private object SingletonHolder {
        val DATA_BUS = LiveDataBus()
    }

    fun <T> with(target: String): BusMutableLiveData<T> {
        if (!bus.containsKey(target)) {
            bus[target] = BusMutableLiveData()
        }
        return bus[target] as BusMutableLiveData<T>
    }

    companion object {
        fun get(): LiveDataBus {
            return SingletonHolder.DATA_BUS
        }
    }

    /**
     * 事件订阅,关注生命周期
     * @param sticky =true 表示当前订阅可以接受订阅前最后发送的结果
     */
    fun <T> observe(target: String, owner: LifecycleOwner, sticky:Boolean=false,observe: (T) -> Unit) {
        with<T>(target).observe(owner, object : BusObserver<T>() {
            override fun onChanged(t: T) {
                if (sticky||mVersion != START_VERSION) {
                    observe.invoke(t)
                }
                super.onChanged(t)
            }
        })
    }


    /**
     * I在activity中,fragment销毁时会自动注销,这里将observeForever和LifeCycle,在生命周期结束时自动注销
     * @param sticky =true 表示当前订阅可以接受订阅前最后发送的结果
     */
    fun <T> observeForever(target: String, owner: LifecycleOwner,sticky:Boolean=false, observeForever: (T) -> Unit) {
        with<T>(target).observeForever(owner, object : BusObserver<T>() {
            override fun onChanged(t: T) {
                if (sticky||mVersion != START_VERSION) {
                    observeForever.invoke(t)
                }
                super.onChanged(t)
            }
        })
    }

    /**
     * 需要手动注销
     * @param sticky =true 表示当前订阅可以接受订阅前最后发送的结果
     */
    fun <T> observeForever(target: String,sticky:Boolean=false, observeForever: (T) -> Unit) {
        with<T>(target).observeForever(object : BusObserver<T>() {
            override fun onChanged(t: T) {
                if (sticky||mVersion != START_VERSION) {
                    observeForever.invoke(t)
                }
                super.onChanged(t)
            }
        })
    }

    init {
        bus = HashMap()
    }

    class BusMutableLiveData<T> : MutableLiveData<T>() {
        private val observerMap = hashMapOf<Observer<in T>, Observer<in T>>()

        /**
         * 自动销毁,它始终处于活动状态,但和生命周期绑定,这意味着给定的观察者将接收所有事件会被自动删除
         */
        fun observeForever(owner: LifecycleOwner, observer: Observer<in T>) {
            if (!observerMap.containsKey(observer)) {
                observerMap[observer] = observer
                owner.lifecycle.addObserver(ForeverLifeCycle(observer))
            }
            super.observeForever(observer)
        }


        inner class ForeverLifeCycle(private val observer: Observer<in T>) :
            LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                if (source.lifecycle.currentState == Lifecycle.State.DESTROYED) {
                    if (observerMap.containsKey(observer)) {
                        removeObserver(observer)
                    }
                }
            }
        }
    }

    /**
     * 因为LiveData源码中,创建监听时会收到前一次的结果,我们并不希望如此,只希望发出通知后才能收到,因为源码Version判断的
     * private void considerNotify(ObserverWrapper observer) {
     *if (!observer.mActive) {
     *return;
     *}
     * Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet.
     *
     * we still first check observer.active to keep it as the entrance for events. So even if
     * the observer moved to an active state, if we've not received that event, we better not
     * notify for a more predictable notification order.
     *if (!observer.shouldBeActive()) {
     *observer.activeStateChanged(false);
     *return;
     *}
     * 这里判断是否发送消息的,observer第一次创建是mLastVersion 默认-1 所以会收到上次发送的结果
     *if (observer.mLastVersion >= mVersion) {
     *return;
     *}
     *observer.mLastVersion = mVersion;
     *observer.mObserver.onChanged((T) mData);
     *}
     * 继承Observer 同样用mVersion来避免收到上一次的结果
     */
    abstract class BusObserver<T> : Observer<T> {
        var mVersion = START_VERSION

        override fun onChanged(t: T) {
            mVersion++
        }
    }
}

sticky=true 是利用LiveData 在创建Observe时会接受最近一次的结果来接受上个界面的数据

使用方式如下:

//发送数据
LiveDataBus.get().with<String>("test").setValue("3333333333333333")

//接受结果
LiveDataBus.get().observeForever<String>("test", this,true) {
            Log.i("asdf", "onCreate: ${it as String}")
        }

//注销
LiveDataBus.get().with<String>("test").removeObserver()

欢迎指正!!!

  • 转载自:https://blog.csdn.net/qq_35327514/article/details/120764143
  • 留言