在我的用例中,我使用与一些常见观察者共享的视图模型。当三个片段添加到返回堆栈时,视图模型将观察到所有三个片段。不过,我只需要观察当前可见的片段即可。
只需要观察当前可见片段中的事件,而不是观察所有其他片段
共享视图模型用于在多个观察之间共享公共数据源。当一个源有多个观察者时,您不应该尝试仅观察当前可见片段的变化。如果这样做,可能会出现数据不一致的情况。
假设你修改了某个fragment中ViewModel中的数据,如果其他fragment停止观察它,它们可能有旧的数据值,但数据发生了变化,因此数据不一致。
你想要做的是观察事件,而不是陈述。你想要消除片段,那是一个事件。要将 LiveData 与事件一起使用,您必须在事件完成时重置该值。因此,当其他观察者观察它时,他们不会发现事件已发生。您可以在这里阅读更多相关信息。下面是一个例子:
为事件状态创建 LiveData
// this is your live data based on which event will occur
val timer = MutableLiveData<Boolean>()
// this is the live data for handling the event
val eventDismissFragment = MutableLiveData<Boolean>()
init{
// initialize event to false
eventDismissFragment.value = false
}
// this is the function that is called when the event occurred
fun onFinish() {
timer.value = 0
eventDismissFragment.value = true
}
// this is for resetting the value of LiveData after event is handled
fun onDismissFragmentComplete() {
eventDismissFragment.value = false
}
观察事件而不是计时器来消除片段
viewModel.eventDismissFragment.observe(viewLifecycleOwner, Observer { isFinished ->
if (isFinished){
// dismiss your fragment here but before dismissing, notify that you handled the event
viewModel.onDismissFragmentComplete()
dismissFragment()
}
})