I want to update my old android project and want to use the recommended way of Google with ViewModel and Livedata. I use Viewpager2 and Tablayout with 4 fragments in it. The first fragment has a ViewModel and observes data changes via Livedata and updates it's UI.
My questions are:
What happens when I swipe to the second fragment in the Viewpager? The first fragment is not visible anymore, but it's still there. Does the lifecyle of fragment1 change when it's not visible? And if not, how can I stop updating it because it would still get update notifications.
Can I use the same ViewModel for all 4 fragments because they just visualize data changes in Livedata in another way. How can I do so?
Thanks!
OK, after some testing, I found the answer.
The lifecyle of the first fragment changes to pause when sliding to the second fragment and back to resume when sliding back. You can use these events and set a bool var to update the ui or not.
You can use the same ViewModel for all fragments. You only have to give attention not to update, when the fragment is not visible. And my case, you can use the lifecyle of the application.