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?
Well! Adding to @ianhanniballake's answer,
In your function,
private fun getCountries(){
// 1
viewModelScope.launch {
val a = model.getAllCountries()
countriesList.value = a
}
}
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()
}
}
withContext
, and after return from withContext
block, we are back on main thread.