Skip to content Skip to sidebar Skip to footer

Fragment Not Receiving Livedata Updates After Remove + Add

I am currently playing around to get a hang of the fragment's lifecycle in relation to ViewModel and LiveData. I have 2 fragments, fragmentA and fragmentB. I add the Observer in th

Solution 1:

As per the Lifecycle.State.DESTROYED documentation:

After this event, this Lifecycle will not dispatch any more events.

I.e., DESTROYED is a terminal state and once it is destroyed, that Lifecycle will always be destroyed.

This means there are two correct ways to do what you want:

  1. Create a new Fragment instance each time you call switchToA or switchToB. Since all the state is destroyed when you remove a Fragment, you aren't gaining anything by reusing Fragment instances.

  2. Don't use replace, but instead use attach() and detach() (i.e., attach the one you want to display, detach the one you want to hide). Fragments keep their state when detached (they aren't destroyed), so re-attaching it will move it back to resumed.

Post a Comment for "Fragment Not Receiving Livedata Updates After Remove + Add"