/**
* 自定订阅 消息不中断的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
}
}
}
}
网友评论