[英]Is there a difference between using GlobalScope.launch and CoroutineScope().launch to launch a coroutine?
There are different ways of launching a coroutine in Kotlin.在 Kotlin 中有多种启动协程的方法。 I found a couple of examples where
GlobalScope
and CoroutineScope
are used.我发现了几个使用
GlobalScope
和CoroutineScope
的例子。 But the latter one is being created directly when launching a coroutine:但是后者是在启动协程时直接创建的:
Using GlobalScope
:使用
GlobalScope
:
fun loadConfiguration() { GlobalScope.launch(Dispatchers.Main) { val config = fetchConfigFromServer() // network request updateConfiguration(config) } }
Using CoroutineScope
instances, created directly when launching a coroutine:使用
CoroutineScope
实例,在启动协程时直接创建:
fun loadConfiguration() { CoroutineScope(Dispatchers.Main).launch { val config = fetchConfigFromServer() // network request updateConfiguration(config) } }
In this case is there a difference between these two approaches?在这种情况下,这两种方法有区别吗?
Doesn't the second case violate the principle of structured concurrency ?第二种情况是不是违反了结构化并发的原则?
Doesn't the second case violate the principle of structured concurrency?
第二种情况是不是违反了结构化并发的原则?
Actually both cases violate it equally, because they have pretty much the exact same semantics.实际上这两种情况同样违反了它,因为它们具有几乎完全相同的语义。 All the warnings against using
GlobalScope.launch
that you may have encountered, apply to CoroutineScope().launch
just the same.您可能遇到的所有反对使用
GlobalScope.launch
的警告同样适用于CoroutineScope().launch
。 A slight difference is that the latter is entirely pointless, whereas the former at least has some legitimate use cases.一个细微的区别是后者完全没有意义,而前者至少有一些合法的用例。
Writing CoroutineScope().launch
instead of GlobalScope.launch
obscures the intent and consequences, as well as creates a needless object every time.编写
CoroutineScope().launch
而不是GlobalScope.launch
会掩盖意图和后果,并且每次都会创建不必要的 object。
I think the CoroutineScope().launch
idiom came into being solely because it circumvented the warnings you get for GlobalScope.launch
.我认为
CoroutineScope().launch
成语的出现仅仅是因为它规避了您对GlobalScope.launch
的警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.