LiveData not updating when changing (back and forth) activities

Viewed 43

Before I post detailed code, I want to make sure I do understand LiveData correctly. I have a MainActivity (A) and then go to 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'.

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.

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?

PS> Forgot to mention that I do see the counter counting down uninterrupted while I'm in 'A' (via LOG.i)

1 Answers

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. Button to go from A > B -> A is alive and a new instance of ViewModel B is created. This new ViewModel of B has no idea the previous ViewModel existed.

Related