如何从 android kotlin 协程获取结果到 UI 线程

Gra*_*zzi 6 android kotlin android-runonuithread kotlin-coroutines

我不明白 kotlin 协程是如何工作的。我需要在异步线程上做很长时间的工作,并在 Android 应用程序的 UI 线程上获取结果。有人可以给我一些例子吗?例如

private fun getCountries(){
        viewModelScope.launch { 
            val a = model.getAllCountries()
            countriesList.value = a
        }
}
Run Code Online (Sandbox Code Playgroud)

午餐 model.getAllCountries() 会异步但最后我怎样才能得到 UI 线程的结果?

Rac*_*hra 5

好!添加到@ianhanniballake 的回答中,

在你的函数中,

private fun getCountries(){
   // 1
   viewModelScope.launch {  
      val a = model.getAllCountries()
      countriesList.value = a
   }
}
Run Code Online (Sandbox Code Playgroud)
  1. 您已经suspend从 viewModel 范围启动了您的函数,并且默认上下文是主线程。

现在suspend fun getAllCountries将在getAllCountries函数定义中指定将工作的线程。

所以它可以写成这样

suspend fun getAllCountries(): Countries {
   // 2
   return withContext(Disptachers.IO) { 
    service.getCountries()
   }
}
Run Code Online (Sandbox Code Playgroud)
  1. 我们使用 指定一个新线程来调用服务器withContext,从withContext块返回后,我们回到主线程。