android - 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)
}
}
解决方案
这是您的代码的外观:
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 提取。
推荐阅读
- javascript - 从 spring 控制器动态创建 HTML 文本框
- express - 如何使用车把编写带有条件的 {{#each}} 语句,是否可以
- html - 尝试在 Angular 中显示后端发送的 SVG
- asp.net-core - Cookie 不会从前端发送到后端
- java - 使用 Java/Spring 连接到 Azure 事件网格和服务总线
- python - 该程序没有正确比较两个数字
- python - SQLite3 和多线程?最好的行动方案是什么?
- c# - EventCounters 是从 .NET 库中公开指标的标准方法吗?
- python - 运行 portal_client 时的 Python 异常
- date - 选择查询中的 Gorm 日期