因此,我让这段代码在“onBindViewHolder”回收器的适配器方法中运行:
launch(UI) {
val bitmapDrawable = loadLargeBitmapDrawable()
imageView.setImageDrawable(bitmapDrawable)
}
这让我的应用卡住了几秒钟,锁定了我的主线程。
但后来我改成了这样:
launch { // <- I removed the "UI"
val bitmapDrawable = loadLargeBitmapDrawable()
launch(UI) { //Launch the UI coroutine inside the other
imageView.setImageDrawable(bitmapDrawable)
}
}
为什么会这样?协同程序的目的是使同一线程 (UI) 内的事物异步,对吧? 有人可以解释为什么我必须在另一个协程范围内运行 UI 协程吗?
最佳答案
The purpose of coroutines are to make things async inside the same thread (UI) right?
您认为协同程序具有比实际更多的魔力。如果您的 loadLargeBitmapDrawable()
函数不可暂停,只是占用其线程直到完成,Kotlin 对此无能为力。当您说 launch(UI)
时,您命令该函数在 UI 线程上运行。
您的第二个示例在 CommonPool
上下文(这是默认设置)中执行,然后将任务发布到 UI 线程;更自然的说法是这样的(我在我的代码中使用它,目的与您完全相同):
launch(UI) {
val bitmapDrawable = withContext(CommonPool) {
loadLargeBitmapDrawable()
}
imageView.setImageDrawable(bitmapDrawable)
}
withContext
将暂停您在 UI 线程上启动的协程,将重量级操作提交到公共(public)线程池,然后使用其结果在 UI 线程上恢复协程。现在您可以将位图推送到 imageView
。
关于android - 为什么这个 Kotlin Coroutine 会卡住界面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48935980/