简体   繁体   English

更改(来回)活动时 LiveData 不更新

[英]LiveData not updating when changing (back and forth) activities

Before I post detailed code, I want to make sure I do understand LiveData correctly.在发布详细代码之前,我想确保我确实正确理解LiveData I have a MainActivity (A) and then go to Activity (B).我有一个 MainActivity (A),然后是 go 到 Activity (B)。 I did implement a ViewModel for 'B' and observe (and display) the MutableLiveData for a Counter (residing in the ViewModel) in Activity 'B'.我确实为“B”实现了一个 ViewModel,并在活动“B”中观察(并显示)计数器(位于 ViewModel 中)的 MutableLiveData。

This works perfect, I do see the countdown in 'B', but when I do the back-button to return to MainActivity 'A' and then go back to 'B', the counter is not updated anymore.这很完美,我确实在“B”中看到了倒计时,但是当我按后退按钮返回 MainActivity“A”然后 go 返回“B”时,计数器不再更新。

I do see the counter pick up nicely when I switch apps ie send it to the background and bring it back.当我切换应用程序时,我确实看到计数器很好地恢复了,即将它发送到后台并带回来。

I might not understand the whole Lifecycle properly, but I thought the beauty of LiveData is that I don't have to worry about all this and once I return to 'B' it should just pick up the observation seamlessly?我可能无法正确理解整个生命周期,但我认为LiveData的美妙之处在于我不必担心这一切,一旦我回到“B”,它应该无缝地接受观察吗?

PS> Forgot to mention that I do see the counter counting down uninterrupted while I'm in 'A' (via LOG.i) PS> 忘了提,当我在“A”时,我确实看到计数器不间断地倒计时(通过 LOG.i)

When you go from A > B -- A is alive B is alive Back button to go to A -> A is alive B is destroyed hence the ViewModel associated with B is destroyed as well.当您从 A > B 开始 go - A 还活着 B 还活着 后退按钮到 go 到 A -> A 还活着 B 被破坏,因此与 B 关联的 ViewModel 也被破坏。 Button to go from A > B -> A is alive and a new instance of ViewModel B is created.从 A > B -> A 到 go 的按钮处于活动状态,并创建了 ViewModel B 的新实例 This new ViewModel of B has no idea the previous ViewModel existed. B 的这个新 ViewModel 不知道之前的 ViewModel 存在。

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

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