Bradleycorn
03/11/2021, 9:55 PMnavigation-compose
and ViewModels. For a time now, we've been able to get a viewmodel scoped to a backstack entry (at first by rolling our own factory, then using a HiltViewModelFactory, and now by using hiltNavGraphViewModel()
). I presume that means that as long as the backstack entry exists, then the VeiwModel will hang around, and won't be cleared until the backstack entry is popped, right?
And if so, you might need to be careful in some cases when launching a coroutine using viewModelScope.launch
, right? If your are just making a newtork call to fetch a piece of data or something, no big deal. But if it's a longer running operation, then it will not get canceled until the backstackentry is popped from the stack. So, if say you have Composables A, B, and C that are entries in your graph, and you navigate from A to B to C ... if the ViewModel for A launched a coroutine in its viewModelScope
, it will still be running while the user is looking at C, correct? So if your intention is to launch a coroutine when the user is looking at A and have it get canceled when the user navigates to B, then you really need to use a different mechanism (like say LaunchedEffect
). Do I have that right?Ian Lake
03/11/2021, 11:32 PMviewModelScope
survives for the entire time the destination is on the back stack and would not be affected by navigating to a new destination, correct. It will be cancelled when you pop the destination off the back stack, also correct.Bradleycorn
03/11/2021, 11:38 PMallan.conda
03/12/2021, 3:36 AMIan Lake
03/12/2021, 3:41 AMsuspend
method that you call within a LaunchedEffect
- that would cancel quite nicely when you navigateKamilH
03/12/2021, 8:33 AMComposable
?Ian Lake
03/12/2021, 3:23 PMBradleycorn
03/12/2021, 7:41 PMsuspend
method that does the polling, and I call it from a LaunchedEffect
in the "Screen" composable, and thus it gets canceled when the user navigates to a "child screen", stopping the polling.Ian Lake
03/12/2021, 7:47 PMBradleycorn
03/12/2021, 7:56 PMLaunchedEffect
remains active if the app goes to the background. I Ian Lake
03/12/2021, 8:07 PM