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

/**
 * 自定订阅 消息不中断的LiveData
 */
class EventMutableLiveData : MutableLiveData(), LifecycleObserver {
    private val map = hashMapOf>>()
    override fun observe(owner: LifecycleOwner, observer: Observer) {
//        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
            }
        }
    }
}

你可能感兴趣的:(解决LiveData observe 处于未激活时无法收到消息)