Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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 ?

like image 764
Yatin Avatar asked Jan 10 '20 10:01

Yatin


People also ask

What is the difference between coroutine scope and Globalscope scope?

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.

What is scope in Kotlin coroutine?

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.

What is the difference between global scope and lifecycle 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.

What is the difference between Globalscope and viewmodelscope?

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.


1 Answers

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.

like image 119
Marko Topolnik Avatar answered Oct 16 '22 17:10

Marko Topolnik