Search code examples
kotlinasynchronousmodelscopewithcontext

How to wait response values in viewModelScope from two suspend functions


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?


Solution

  • 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
        }
    }