Hi guys, Does you guys know what the difference be...
# coroutines
t
Hi guys, Does you guys know what the difference between coroutineScope and viewmodelScope?
j
What
coroutineScope
are you referring to?
t
Because it see it in a program on github. but i don't know what the coroutineScope in this case. Can you help me resolve this one?
message has been deleted
j
This is the coroutineScope function of kotlinx.coroutines. It is not a variable. It is a suspending function that provides a short-lived coroutine scope in which you can start some coroutines (e.g. for parallel decomposition of work), and waits for all those coroutines to finish before
coroutineScope
itself completes.
viewModelScope
, on the other hand, is a property of type
CoroutineScope
provided by some Android components. It is a coroutine scope whose lifecycle is tied to that of the view model you're using it in. It allows to start coroutines that will be automatically cancelled when the view model is not used anymore.
Technically here
coroutineScope
is not required per se, because
launch
already provides a scope, but the author wanted to catch exceptions thrown by the network calls done in
async { }
coroutines. If the
async
coroutines were started directly in the scope of
launch
, there would be no way to catch these exceptions.
t
I got it
Your answer is very easy to understand, thank you so much