简体   繁体   English

Kotlin 中 globalScope 、 cooruntineScope 和 viewScope 之间的区别

[英]Difference between globalScope , corountineScope and viewScope in Kotlin

What is the difference between globalScope , coroutineScope and viewModelScope and when to use them inside Kotlin programming with viewModelScope still under development? globalScope 、 coroutineScope 和 viewModelScope 之间有什么区别,以及何时在 Kotlin 编程中使用它们,而 viewModelScope 仍在开发中?

I have gone through below link https://medium.com/androiddevelopers/coroutines-on-android-part-iii-real-work-2ba8a2ec2f45我已经通过以下链接https://medium.com/androiddevelopers/coroutines-on-android-part-iii-real-work-2ba8a2ec2f45

I know corountineScope will be having scope until {} for which it was called.我知道 cooruntineScope 将在调用它的 {} 之前拥有范围。 Also we have supervisorScope which is similar to coroutineScope , viewModelScope having scope till ViewModel .我们还有 supervisorScope ,它类似于 coroutineScope , viewModelScope 的范围直到 ViewModel 。 Global scope - does it have till application works or activity ?全球范围 - 它是否有直到应用程序工作或活动?

GlobalScope is a singleton scope that returns a completely empty coroutineContext . GlobalScope是一个单例作用域,它返回一个完全空的coroutineContext Since there's no Job associated with it, you cannot cancel it, so its lifecycle is basically "forever".由于没有与之关联的Job ,您无法取消它,因此它的生命周期基本上是“永远”的。

A separate instance of viewModelScope is attached to every instance of ViewModel .一个单独的viewModelScope实例附加到ViewModel每个实例。 It runs out when the ViewModel is destroyed.ViewModel被销毁时它就用完了。

coroutineScope and supervisorScope are suspendable functions that establish their own local scope, run the block you pass to them within that scope, and return when all the work inside is done, including all the coroutines launched within their scope. coroutineScopesupervisorScope是可挂起的函数,它们建立自己的本地范围,在该范围内运行您传递给它们的块,并在内部的所有工作完成后返回,包括在其范围内启动的所有协程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM