CoroutineScope 和 GlobalScope 在生命周期方面的区别

huangapple go评论50阅读模式
英文:

CoroutineScope and GlobalScope differences in terms of lifecycle

问题

我明白GlobalScope与应用程序生命周期相关,只要应用程序存在,但是CoroutineScope似乎与任何生命周期都没有关联,所以,如果我使用它们之一启动协程,真正的区别是什么?似乎使用CoroutineScope启动协程与使用GlobalScope并没有太大区别。

英文:

I understand that GlobalScope is tied an application lifecycle, so as long as the application is alife, but then, CoroutineScope doesn't seem to be tied to any lifecycle at all, so, if I launch a coroutine with either of them, what is the real difference? Seems that launching a coroutine with CoroutineScope isn't much different from doing it with GlobalScope.

答案1

得分: 1

如果您创建了一个CoroutineScope,则需要手动管理它的生命周期,如果不再需要它,就应该取消它。这就是使用CoroutineScope创建的范围的预期使用方式。因此,这些范围具有适当的生命周期,但只要您正确使用它们。

另一方面,GlobalScope是一种特殊类型的CoroutineScope,预期一直处于活动状态。它没有设计生命周期。

如果您看到有人用CoroutineScope().launch()替换了GlobalScope.launch(),那么是的,您是正确的 - 这几乎是相同的。人们不理解这一点,因此他们认为只是因为IDE不再显示警告而解决了问题。

英文:

If you create a CoroutineScope, you are expected to manage its lifecycle manually and cancel it if it is not needed anymore. This is how scopes created with CoroutineScope are meant to be used. So these scopes have a proper lifecycle, but only as long as you use them properly.

GlobalScope on the other hand is a special type of CoroutineScope which is expected to be active all the time. It doesn't have a lifecycle by design.

If you see someone replaces GlobalScope.launch() which something like CoroutineScope().launch(), then yes, you are correct - this is almost the same. People don't understand this, so they think they fixed the problem only because IDE doesn't show a warning anymore.

huangapple
  • 本文由 发表于 2023年2月19日 17:02:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499030.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定