I have code like
viewModelScope.launch(exceptionHandler) {
withContext(Dispatchers.IO){
val name = fetchName() //suspend fun
val surname = fetchSurname() //suspend fun
}
//how to wait response from name and surname to use it in another call?
//name and surname must be async
}
private suspend fun fetchName(): Name {
return withContext(Dispatchers.IO) {
//db
}
}
private suspend fun fetchSurname(): Surname {
return withContext(Dispatchers.IO) {
//db
}
}
How to wait response from name and surname to use it in another call?
I assume your code is equivalent to
viewModelScope.launch(Dispatcher.IO)
Therefore everything inside your
launch
block is executed sequentially, because it is simply one coroutine. It means that any code in the block afterwill execute only after
fetchName
andfetchSurname
complete. If you want to update some UI after it, for example, you can useIf you want to use it as a property in the view model consider using
Flow
UPD: For your specific case