英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论