我有以下代码:
lifecycleScope.launch(Dispatchers.Default) {
val specialMessage = URL("https://finepointmobile.com/api/inventory/v1/message").readText()
d("Globby", "The message is: $specialMessage")
lastSavedProduct.text = specialMessage //line 41
}
但是执行时出现以下错误:
ERROR : android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at com.example.MainActivity$onCreate$2.invokeSuspend(MainActivity.kt:41)
我尝试将
lifecycleScope.launch(Dispatchers.IO)
更改为lifecycleScope.launch(Dispatchers.Default)
,但不起作用。 最佳答案
如果我正确记得协程,那么以下方法应该起作用:
lifecycleScope.launch { // runs on Main by default
val specialMessage = withContext(Dispatchers.IO) {
URL("https://finepointmobile.com/api/inventory/v1/message").readText()
}
lastSavedProduct.text = specialMessage
}