I’m trying to grasp how the lifecycle for the comp...
# compose
m
I’m trying to grasp how the lifecycle for the composables works comparing to the traditional lifecycle of activity or fragment. Let’s say that I have functionality that is fetching data from the backend every second while the screen is visible. For example, with activity/fragment I would start fetching data in onResume and I would stop it in onPause. How should I implement such functionality with Compose? When I’m using navigation components then viewmodel is still alive even when another screen is pushed above the one that should be stopped. Could somebody explain this to me? Thanks.
g
The viewmodel is linked to some lifecycle and will be alive accordingly. If you're using a single viewmodel for the whole app, it should know which screen is being shown (since it should be the single source of truth for the UI state). Since it knows, it can tell your repository to stop fetching data.
m
What if I’m using standalone viewmodel for each screen?
g
Since the event that leads to navigating to the next screen will flow up to the view model, it knows when it should stop fetching data.