How get result to UI Thread from an android kotlin coroutines

As per the documentation for viewModelScope:

This scope is bound to Dispatchers.Main.immediate

Where Dispatchers.Main is the Kotlin way of saying 'the main thread'. This means that, by default, all of the code in the launch block runs on the main thread. Your getAllCountries(), if it wants to run on a different thread, would want to use withContext(Disptachers.IO) to move to the IO coroutine dispatcher, as an example.

Therefore in this case, the result of your method is already on the main thread and there's nothing else you need to do.


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.