[英]Fragment Recreation causes Observer to trigger onChanged() with Androidx Navigation library
Issue: 问题:
While working with Navigation
Library, I observed when I navigate back to the previous fragment, it recreates the fragment and thus re-registering all my Observers
which triggers OnChanged()
again 在使用
Navigation
库时,我观察到导航回到上一个片段时,它会重新创建该片段,并因此重新注册我的所有Observers
,从而再次触发OnChanged()
I have a Snackbar
which shows some error messages example if I am looking for no more data present or no Internet connection to the server: 我有一个
Snackbar
,如果我正在寻找不存在的数据或服务器没有Internet连接,它会显示一些错误消息示例:
deliveriesListViewModel.isMoreDataPresent.observe(this, Observer {
if (!it) showSnackBar(getString(R.string.no_more_data))
})
Source of above code here 以上代码的来源在这里
And on navigating back and forth, the SnackBar
pops up every time, and also every time I change the orientation or rotate my device. 在来回导航时,
SnackBar
每次都会弹出,并且每次我更改方向或旋转设备时都会弹出。
My architecture has a single Activity
with startDestination
as my ListFragment
in the navigation graph and a DetailFragment
as destination
. 我的体系结构在导航图中有一个
Activity
其中startDestination
作为我的ListFragment
,一个DetailFragment
作为destination
。 SupportNavigationUp
or a simple OnBackPressed
on DetailFragment
returns me to my ListFragment
and then recreates the fragment and thus re-registering all my Observers
which triggers OnChanged()
again and the SnackBar
pops up when noMoreDataPresent
LiveData
is false SupportNavigationUp
或简单OnBackPressed
上DetailFragment
返回我到我的ListFragment
,然后重新创建片段,从而重新注册我所有的Observers
触发OnChanged()
再次和SnackBar
弹出时noMoreDataPresent
LiveData
是假的
Now I tried the solution from here but unfortunately, it doesn't work 现在我从这里尝试了解决方案,但是不幸的是,它没有用
I have also tried to switch my LifecycleOwner
to my activity by that also doesn't work. 我也尝试过将
LifecycleOwner
切换到我的活动,这也无效。 Tried moving the ViewModelProviders.of
to OnCreate
and onActivityCreated
- doesn't work 尝试将
ViewModelProviders.of
移至OnCreate
和onActivityCreated
不起作用
Please suggest corrections or any ideas what can be done to prevent SnackBar popping up after navigation and orientation change. 请提出更正或任何建议,以防止SnackBar在导航和方向更改后弹出。
Footnotes 脚注
I have gone through these issues: 我经历了以下问题:
This article , especially item 1, might be relevant to what you're experiencing. 本文 ,尤其是第 1条,可能与您所遇到的有关。 Basically, what happens is that you may have multiple spawned Observers every time you navigate back to your fragment, thus executing
onChanged
multiple times. 基本上,发生的情况是,每次导航回到片段时,您可能都有多个生成的观察者,从而多次执行
onChanged
。 Using the fragment's view lifecycle as the LifecycleOwner
should prevent this from happening, so your code above would look like this: 将片段的视图生命周期用作
LifecycleOwner
应该可以防止这种情况的发生,因此上面的代码如下所示:
deliveriesListViewModel.isMoreDataPresent.observe(viewLifecycleOwner, Observer {
if (!it) showSnackBar(getString(R.string.no_more_data))
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.