How get result to UI Thread from an android kotlin coroutines

Graziano Rizzi picture Graziano Rizzi · Oct 7, 2019 · Viewed 7.4k times · Source

I didn't understand how kotlin coroutines work. I need to do a long work on an asynchronous thread and get the result on the UI Thread in an Android app. Can someone give me some examples? For example

private fun getCountries(){
        viewModelScope.launch { 
            val a = model.getAllCountries()
            countriesList.value = a
        }
}

will lunch model.getAllCountries() async but in the end how can i get result to UI Thread?

Answer

Rachit Mishra picture Rachit Mishra · Oct 7, 2019

Well! Adding to @ianhanniballake's answer,

In your function,

private fun getCountries(){
   // 1
   viewModelScope.launch {  
      val a = model.getAllCountries()
      countriesList.value = a
   }
}
  1. You have launched your suspend function from viewModel scope, and the default context is the main thread.

Now the thread on which suspend fun getAllCountries will work will be specified in the definition of getAllCountries function.

So it can be written something like

suspend fun getAllCountries(): Countries {
   // 2
   return withContext(Disptachers.IO) { 
    service.getCountries()
   }
}
  1. We specify a new thread to call the server using withContext, and after return from withContext block, we are back on main thread.