如何在`viewModelScope`中等待来自两个挂起函数的响应值

huangapple go评论58阅读模式
英文:

How to wait response values in viewModelScope from two suspend functions

问题

如何等待namesurname的响应以在另一个调用中使用它们?

英文:

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() // 挂起函数
}

只有在fetchNamefetchSurname完成后才会执行。如果你想在之后更新一些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
    }
}

huangapple
  • 本文由 发表于 2023年3月15日 20:20:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744613.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定