我有这样的代码
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
}
}
如何等待名字和姓氏的响应以在另一个电话中使用它?
我假设你的代码等同于
viewModelScope.launch(Dispatcher.IO)
因此,
launch
块中的所有内容都按顺序执行,因为它只是一个协程。这意味着块中的任何代码都在之后
withContext(Dispatchers.IO){ // Place it in your launch block
val name = fetchName() //suspend fun
val surname = fetchSurname() //suspend fun
}
只会在fetchName
和
fetchSurname
完成后执行。例如,如果你想在它之后更新一些 UI,你可以使用
withContext(Dispatchers.Main) {
textView1.text = name
textView2.text = surname
}
如果您想将它用作视图模型中的属性,请考虑使用Flow
更新: 针对您的具体情况
viewModelScope.launch(exceptionHandler) {
withContext(Dispatchers.IO){
val name = fetchName() //suspend fun
val surname = fetchSurname() //suspend fun
apiCall(name, surname) // it will execute only after name and surname are fetched
}
}