Ofir Bar
03/12/2020, 8:57 AMViewModel
in the image below, calling methods on some repository.
All methods attempt to do the same thing:
Fetch a value from the local DB (a Room DB), suspend the method execution until that value is fetched so the method is guaranteed to return a value.
In each method I added a comment that specifies what issue I have with this method.
What is the safe and correct way to accomplish what I am trying to do?
Slack ConversationEvan R.
03/12/2020, 12:01 PMlaunch
is a fire-and-forget construct which exits immediately after you invoke it, so it’s not guaranteed that your viewModelScope.launch
will run or complete before your function returns in getCityByID
. What you probably want to do there is turn getCityByID
into a suspend fun
and just do something to the effect of:
val city = withContext(viewModelScope) {
locationRepository.getSingleCityFromDatabaseByID(selectedCityID)
}
return city
if you need to run that inside the viewModelScope and not the caller’s scope. If you’d rather run in the caller’s scope you can simply do:
return locationRepository.getSingleCityFromDatabaseByID(selectedCityID)
as long as you make it a suspend fun
.
Same concept applies across your other two functions as well.Evan R.
03/12/2020, 12:02 PMrunBlocking(viewModelScope) { …
Evan R.
03/12/2020, 12:02 PMEvan R.
03/12/2020, 12:03 PMOfir Bar
03/12/2020, 3:43 PMEvan R.
03/12/2020, 3:44 PMOfir Bar
03/12/2020, 5:03 PMsuspend fun test(selectedCityId: Int, selectedLanguages: List<Int>, selectedExpertiseFieldId: Int){
val city = withContext(viewModelScope){
locationRepository.getSingleCityFromDatabaseByID(selectedCityID)
}
return city
}
Ofir Bar
03/12/2020, 5:03 PMEvan R.
03/12/2020, 5:05 PMviewModelScope.context
dfriehs
03/13/2020, 7:35 AMasync
instead of launch:
suspend fun getCityById(selectedCityId: Int): City =
viewModelScope.async {
locationRepository.getSingleCityFromDatabaseByID(selectedCityID)
}.await()
Ofir Bar
03/13/2020, 9:14 AMlaunch
?
I assume I implicitly did that when calling withContext
am I correct?dfriehs
03/13/2020, 9:16 AMlaunch
in your initial example; I am not exactly sure about implementation details of withContext
, sadly.Ofir Bar
03/13/2020, 9:24 AM