英文:
How to wait response values in viewModelScope from two suspend functions
问题
如何等待name
和surname
的响应以在另一个调用中使用它们?
英文:
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?
答案1
得分: 2
我假设你的代码等同于
viewModelScope.launch(Dispatcher.IO)
因此,在你的launch
块内的所有代码都是顺序执行的,因为它只是一个协程。这意味着在以下代码块之后的任何代码
withContext(Dispatchers.IO) {
val name = fetchName() // 挂起函数
val surname = fetchSurname() // 挂起函数
}
只有在fetchName
和fetchSurname
完成后才会执行。如果你想在之后更新一些UI,例如,你可以使用
withContext(Dispatchers.Main) {
textView1.text = name
textView2.text = surname
}
如果你想将其用作视图模型中的属性,考虑使用Flow
更新: 对于你的特定情况
viewModelScope.launch(exceptionHandler) {
withContext(Dispatchers.IO) {
val name = fetchName() // 挂起函数
val surname = fetchSurname() // 挂起函数
apiCall(name, surname) // 仅在获取名字和姓氏后才执行
}
}
英文:
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 after
withContext(Dispatchers.IO){ // Place it in your launch block
val name = fetchName() //suspend fun
val surname = fetchSurname() //suspend fun
}
will execute only after fetchName
and fetchSurname
complete. If you want to update some UI after it, for example, you can use
withContext(Dispatchers.Main) {
textView1.text = name
textView2.text = surname
}
If you want to use it as a property in the view model consider using Flow
UPD: For your specific case
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
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论