Some fragment observers trigger after pop from back stack although data is not changed

让人想犯罪 __ 提交于 2020-05-21 07:25:47

问题


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.

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?


回答1:


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

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).

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.



来源:https://stackoverflow.com/questions/59205879/some-fragment-observers-trigger-after-pop-from-back-stack-although-data-is-not-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!