What is the difference between globalScope , coroutineScope and viewModelScope and when to use them inside Kotlin programming with viewModelScope still under development?
I have gone through below link 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. Also we have supervisorScope which is similar to coroutineScope , viewModelScope having scope till ViewModel . Global scope - does it have till application works or activity ?
Coroutine scope promotes structured concurrency, whereby you can launch multiple coroutines in the same scope and cancel the scope (which in turn cancels all the coroutines within that scope) if the need be. On the contrary, a GlobalScope coroutine is akin to a thread, where you need to keep a reference in-order to join () or cancel () it.
Scope in Kotlin’s coroutines can be defined as the restrictions within which the Kotlin coroutines are being executed. Scopes help to predict the lifecycle of the coroutines. There are basically 3 scopes in Kotlin coroutines: Global Scope. LifeCycle Scope. ViewModel Scope.
LifeCycle Scope The lifecycle scope is the same as the global scope, but the only difference is that when we use the lifecycle scope, all the coroutines launched within the activity also dies when the activity dies. It is beneficial as our coroutines will not keep running even after our activity dies.
GlobalScope is a singleton scope that returns a completely empty coroutineContext. Since there's no Job associated with it, you cannot cancel it, so its lifecycle is basically "forever". A separate instance of viewModelScope is attached to every instance of ViewModel.
GlobalScope
is a singleton scope that returns a completely empty coroutineContext
. Since there's no Job
associated with it, you cannot cancel it, so its lifecycle is basically "forever".
A separate instance of viewModelScope
is attached to every instance of ViewModel
. It runs out when the ViewModel
is destroyed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With