首页 > 解决方案 > Kotlin 协程为什么在 coroutinescope 中使用上下文?

问题描述

我只是编写代码并使用异步并等待下载图像。但是 android studio 告诉我为此使用 withcontext 。你可以看到下面的代码。但是代码中已经有一个 dispatchers.IO 了。我们已经在 IO Scope 中了,为什么还要使用 withContext 呢?这真的是很好的做法吗?代码看起来很奇怪。

CoroutineScope(Dispatchers.IO).launch {
        val test = withContext(Dispatchers.IO) {
            val link =
                "https://i.pinimg.com/originals/3b/8a/d2/3b8ad2c7b1be2caf24321c852103598a.jpg"
            ImageProgress.downloadImageToBitmap(link, this@MainActivity)
        }

        runOnUiThread {
            Glide.with(this@MainActivity)
                .load(test)
                .into(binding.imageView)
        }
    }

标签: androidkotlinkotlin-coroutines

解决方案


这是您的代码的外观:

GlobalScope.launch(Dispatchers.Main) {
        val test = withContext(Dispatchers.IO) {
            val link = "https://i.pinimg.com/originals[...].jpg"
            ImageProgress.downloadImageToBitmap(link, this@MainActivity)
        }
        Glide.with(this@MainActivity)
             .load(test)
             .into(binding.imageView)
    }

注意我不需要runOnGuiThread,因为我指定了Main调度程序,然后暂时切换到IO仅用于阻塞操作。

最后,您还应该避免GlobalScope在生产应用程序中,因为如果阻塞 IO 操作需要很长时间,并且用户不断重复导致应用程序发出请求的操作,您的代码将导致泄漏。

您应该有办法彻底取消 URL 提取。


推荐阅读