Trying to understand why is this ``` suspend fun l...
# getting-started
g
Trying to understand why is this
Copy code
suspend fun loadTwoThings() = coroutineScope {
   val job1 = async { getDataOne() }
   val job2 = async { getDataTwo() }
   saveData(job1.await(), job2.await())
}
different from this
Copy code
suspend fun loadTwoThings() = {
   val job1 = async { getDataOne() }
   val job2 = async { getDataTwo() }
   saveData(job1.await(), job2.await())
}
As I understand, if I cancel a coroutine that called
loadTwoThings
, without coroutineScope the two async will keep running. Also, if one async fails it will let the other keep running. Why is that? A failed child is supposed to cancel its parent, and a cancelled parent is supposed to cancel its children. Are the two asyncs not children of the main coroutine? What exactly does
coroutineScope
do that makes a difference?
d
CoroutineScope
is basically a way to implicitly/easily pass down context to child coroutines.
Without it, you would have to manually create a parent job and then pass it into the
async
coroutine builder to establish a parent/child relationship.
g
so by default, simply using async/launch does not mean they will be children of the parent coroutine? Who is their parent then?
d
Before structured concurrency, yes, they would have no parents.
Now with structured concurrency, it's a bit harder to create a coroutine without a parent.
g
So who is the parent of the asyncs if I don't use the coroutineScope block ?
d
That shouldn't compile. (Unless you're using the old version of the library).
g
aaah it just clicked. I was using this inside a class implementing CoroutineScope, which means the asyncs did in fact have a different parent. So that means that coroutineScope allows you to switch the context to the one you're currently in ?
d
In this case, yes it does.
g
perfect, it all makes a little more sense now
thanks!
d
Although, I recommend against implementing
CoroutineScope
directly.
g
why is that ?
I thought having your ViewModel implement CoroutineScope was a recommended pattern ?
d
It's meant to be a private thing, you don't really want to expose it to callers. Also, it's clearer to specify the scope of a coroutine at build sight. (As you;ve just observed 🙂 )
There's a
viewModelScope
variable you can use.
g
what about other classes or non-Android ViewModels?
d
This is just my (and some other's) opinion btw.
Make a member variable.