robnik
04/29/2021, 5:49 PMviewModelScope.launch { }
run in the same thread? I'm wondering how to avoid loading data twice in my ViewModel. I could have a property there, isLoading
, but I'm not sure how much I need to worry about thread safety.Francesc
04/29/2021, 5:56 PMviewmodelScope.launch
runs on the Main dispatcher, but the suspend block could be changing dispatchers and run the code on a different thread. You can't know that and should not care either.
launch
returns a Job
, you could hold a reference to that to know if you've already launched the coroutinerobnik
04/29/2021, 6:06 PMJob
, that transfers my doubts to the scope that calls the ViewModel. Is the Composable fun
always running in the same thread? So I can just check if (job != null) { ... }
?Francesc
04/29/2021, 6:07 PMrobnik
04/29/2021, 6:11 PMvehicleID: String
. From there I need to load some data from a server. The ID and data are properties of the view model. The data is null, until it's loaded from the network. If I just do a simple if (data == null) load()
, then load()
gets called too many times.robnik
04/29/2021, 6:12 PMFrancesc
04/29/2021, 6:16 PMEffects
are for. You can use a LaunchedEffect
to trigger the load in your viewmodel. This will run once the composable enters the composition for the first time.
See https://developer.android.com/jetpack/compose/lifecycle for detailsFrancesc
04/29/2021, 6:19 PMrobnik
04/29/2021, 6:26 PMIan Lake
04/29/2021, 9:13 PMinit
block?
class VehicleViewModel(savedStateHandle: SavedStateHandle) {
init {
// Use the same string as you have in your route argument i.e., vehicle/{vehicleID}
val vehicleId = savedStateHandle.get("vehicleID")
viewModelScope.launch {
// Load your data
}
}
}
robnik
04/29/2021, 10:41 PMcomposable(route) { }
and setting the vehicleID from the nav arg, inside the braces. Now I see that if I call viewModel()
inside the braces, I get the nav args in the state as you show. But... I want to navigate to another page and keep this ViewModel. The first page is like "vehicle details" and the next page is drilling down further into more details.Ian Lake
04/29/2021, 10:44 PMIan Lake
04/29/2021, 10:45 PMIan Lake
04/29/2021, 10:46 PMFlow
based observable pattern and that reads from a source that properly handles process death and recreationrobnik
04/29/2021, 10:49 PMrobnik
04/29/2021, 10:52 PMIan Lake
04/29/2021, 11:03 PMIan Lake
04/29/2021, 11:04 PM