尽管未更改数据,但某些片段观察器从后台堆栈弹出后触发 [英] Some fragment observers trigger after pop from back stack although data is not changed

查看:95
本文介绍了尽管未更改数据,但某些片段观察器从后台堆栈弹出后触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Kotlin的嵌套片段中遇到了一些问题.我已经用ViewModel嵌套了片段.从后退按钮恢复片段后,尽管我的数据没有更改,但再次按下viewModel LiveData上的所有观察者触发器.

I have some problem in nested fragment in Kotlin. I have nested fragment with ViewModel. After resuming fragment from back button press all observers on viewModel LiveData triggers again although my data does not changed.

首先我用谷歌搜索并尝试在字段变量中定义观察者,并检查它是否已初始化,然后不再观察它: lateinit var观察者:观察者

First i googled and tried for define observer in filed variable and check if it is initialized then do not observer it again: lateinit var observer: Observer

fun method(){
        if (::observer.isInitialized) return
        observer = Observer{ ... }
        viewModel.x_live_data.observe(viewLifecycleOwner ,observer)
}

因此,首先进入片段时它可以正常工作,而且在恢复后它不会在没有数据更改的情况下再次触发,但是在数据更改时也不会触发! 发生了什么事?

So at first enter to fragment it works fine and also after resume it does not trigger again without data change but it does not trigger also on data change! What is going on?

推荐答案

LiveData始终存储最后一个值,并将其发送给每个已注册的观察者.这样,所有观察者都具有最新状态.

LiveData always stores the last value and sends it to each Observer that is registered. That way all Observers have the latest state.

在使用viewLifecycleOwner时,先前的Observer已被破坏,因此注册新的Observer绝对是正确的事情-您需要新的Observer及其现有状态来填充在之后创建的新视图您可以返回Fragment(因为将Fragment放回堆栈时会破坏原始视图).

As you're using viewLifecycleOwner, your previous Observer has been destroyed, so registering a new Observer is absolutely the correct thing to do - you need the new Observer and its existing state to populate the new views that are created after you go back to the Fragment (since the original Views are destroyed when the Fragment is put on the back stack).

如果您尝试将LiveData用于事件(即,仅应处理一次的值),则LiveData并不是最佳的API,因为您必须创建

If you're attempting to use LiveData for events (i.e., values that should only be processed once), LiveData isn't the best API for that as you must create an event wrapper or something similar to ensure that it is only processed once.

这篇关于尽管未更改数据,但某些片段观察器从后台堆栈弹出后触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆