android - 为什么这个 Kotlin Coroutine 会卡住界面?

标签 android kotlin kotlin-coroutines

因此,我让这段代码在“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/

相关文章:

java - 在RelativeLayout中使单个View可见

javascript - Ionic 3 - 下载文件到目录

java - 重构代码以不抛出 Mockito 的 UnnecessaryStubbingException

android - 如何在 kotlin Activity 中获取 ListPreference 值

kotlin-coroutines - jOOQ 是否与 Kotlin 协程配合得很好?

kotlin - 组合 Flow 和非 Flow api 响应 Kotlin

kotlin - Kotlin 协程中 IO 和 UI 之间切换的正确方法是什么?

java - 在 Activity 中使用 Thread 计算整数并在 View 中更新 Canvas

安卓AIDL客户端

android - 运行gradle时未找到kotlinx.android.synthetic