Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading