IllegalArgumentException: Cannot add the same observer with different lifecycles

场景:dialogfragment(tabLayout+viewpager) + 两个Afragment

解决方案一:
class SafeMutableLiveData : MutableLiveData() {

private var weakLifecycleOwner: WeakReference? = null

override fun observe(owner: LifecycleOwner, observer: Observer) {
    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 也可以解决这种问题

你可能感兴趣的:(IllegalArgumentException: Cannot add the same observer with different lifecycles)