当在主线程中使用协程时,一定要使用Dispatchers.Main,在子线程中使用协程时,最好使用Dispatchers.IO。
以下是一个使用协程并避免冻结的示例代码:
GlobalScope.launch(Dispatchers.Main) {
// 在主线程中执行任务
val result = getResult()
displayResult(result)
}
suspend fun getResult(): String = withContext(Dispatchers.IO) {
// 在子线程中执行任务
// 模拟长时间的网络请求
delay(5000)
"Success"
}
fun displayResult(result: String) {
// 在主线程中更新UI
textView.text = result
}