Created
April 1, 2020 01:24
-
-
Save CodeK1988/a7e35bcb1301dd34714355c504425c01 to your computer and use it in GitHub Desktop.
IllegalArgumentException: Cannot add the same observer with different lifecycles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
场景: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 也可以解决这种问题 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment