解决LiveData observe 处于未激活时无法收到消息

2020-07-21  本文已影响0人  淹死丶的鱼
/**
 * 自定订阅 消息不中断的LiveData
 */
class EventMutableLiveData<T> : MutableLiveData<T>(), LifecycleObserver {
    private val map = hashMapOf<LifecycleOwner, ArrayList<Observer<in T>>>()
    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
//        super.observe(owner, observer)
        map[owner] = map[owner] ?: arrayListOf()
        map[owner]?.add(observer)
        observeForever(observer)
        /**
         * 绑定生命周期
         */
        owner.lifecycle.addObserver(this)
    }

    /**
     * 销毁的时候清除LifecycleOwner下的所有订阅者
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy(owner: LifecycleOwner) {
        for (key in map.keys) {
            if (owner == key) {
                map.remove(key)?.forEach { removeObserver(it) }
                owner.lifecycle.removeObserver(this)
                break
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读