为什么这个 Kotlin Coroutine 会卡住界面?
Why this Kotlin Coroutine is freezing the interface?
所以,我在 "onBindViewHolder" 回收商的适配器方法中 运行ning 了这段代码:
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线程上启动的协程,将重量级操作提交到公共线程池,然后在UI线程上恢复协程及其结果.现在您可以将位图推送到 imageView
.
所以,我在 "onBindViewHolder" 回收商的适配器方法中 运行ning 了这段代码:
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线程上启动的协程,将重量级操作提交到公共线程池,然后在UI线程上恢复协程及其结果.现在您可以将位图推送到 imageView
.