ViewModel观察到每个返回片段



我有一个MainActivity,它包含5个带有ViewPager的片段(片段A、片段B、片段C….E(。FragmentA具有viewModel并观察称为";showPopupSuccess";在完成任务后设置为true。

问题是当我转到FragmentC,然后返回FragmentA时。弹出窗口再次显示,因为观察者看起来像";重新激活";。如何摆脱这种情况?我希望重新设置mutableLiveData。所以它没有价值,也没有显示弹出

如果你想进一步了解,这就是bug的视频https://www.youtube.com/watch?v=Ay1IIQgOOtk

解决问题的最简单方法:使用Event包装器代替";复位";对于LiveData,您可以在第一次观察时将其内容标记为handled。然后你反复的观察就知道它已经被处理了,可以忽略它

为了根据指南创建更好的答案,我将从链接文章中复制相关信息:

包装器:

/**
* Used as a wrapper for data that is exposed via a LiveData that represents an event.
*/
open class Event<out T>(private val content: T) {
var hasBeenHandled = false
private set // Allow external read but not write
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
fun peekContent(): T = content
}

在ViewModel中:

// Instead of Boolean the type of Event could be popup
// parameters or whatever else.
private val _showSuccess = MutableLiveData<Event<Boolean>>()
val showSuccess : LiveData<Event<Boolean>>
get() = _showSuccess

在片段中:

myViewModel.showSuccess.observe(viewLifecycleOwner, Observer {
it.getContentIfNotHandled()?.let {
// This is only executed if the event has never been handled
showSuccess(...)
}
})

最新更新