Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save CodeK1988/a7e35bcb1301dd34714355c504425c01 to your computer and use it in GitHub Desktop.
Save CodeK1988/a7e35bcb1301dd34714355c504425c01 to your computer and use it in GitHub Desktop.
IllegalArgumentException: Cannot add the same observer with different lifecycles
场景: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