简体   繁体   English

从 LiveData 仅调用一次 postValue 时多次触发观察者

[英]Observer is triggered multiple times when calling postValue only once from LiveData

I'm using an AndroidViewModel with a LiveData that is observed in a Fragment.我正在使用带有在片段中观察到的 LiveData 的 AndroidViewModel。

However, even though I'm using postValue from the LiveData, the observer registered in an activity triggers more than once.但是,即使我使用 LiveData 中的 postValue,在活动中注册的观察者也会多次触发。 I know it's a common problem on LiveData but I haven't found yet a concrete solution.我知道这是 LiveData 上的一个常见问题,但我还没有找到具体的解决方案。

Does somebody know why this happens?有人知道为什么会这样吗?

Note: u need to provide the code.注意:您需要提供代码。

Answer回答

multiple triggers Causes:多重触发原因:

  1. [Default] onChange() method in the observer will be called when the fragment is created (u will receive the last value emitted before the fragment get destroyed) [默认] 观察者中的 onChange() 方法将在片段创建时被调用(你将收到片段被销毁之前发出的最后一个值)
  2. Or, you are using livedata.observe(this,...), (if it's true you need to use livedata.observe(viewlifecycleowner,...)或者,您正在使用 livedata.observe(this,...),(如果是真的,您需要使用 livedata.observe(viewlifecycleowner,...)

Resource: https://proandroiddev.com/5-common-mistakes-when-using-architecture-components-403e9899f4cb资源: https://proandroiddev.com/5-common-mistakes-when-using-architecture-components-403e9899f4cb

https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150 https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150

https://medium.com/androiddevelopers/viewmodels-and-livedata-patterns-antipatterns-21efaef74a54 https://medium.com/androiddevelopers/viewmodels-and-livedata-patterns-antipatterns-21efaef74a54

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM