场景:dialogfragment(tabLayout+viewpager) + 两个Afragment
解决方案一:
class SafeMutableLiveData<T> : MutableLiveData<T>() {
private var weakLifecycleOwner: WeakReference<LifecycleOwner>? = null
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
weakLifecycleOwner?.get()?.let {
removeObservers(it)
}
weakLifecycleOwner = WeakReference(owner)
super.observe(owner, observer)
}
override fun setValue(value: T) {
try {
super.setValue(value)
} catch (e: Exception) {
super.postValue(value)
}
}}
解决方案二
onViewCreated setUserVisibleHint 判断 if (userVisibleHint && isVisible) viewmodel 实现observe 也可以解决这种问题