Kulwinder Singh
11/01/2018, 8:18 AMlaunch
builder but now inside this builder i'm confused with async
, withContext
and coroutineScope
like what is best for which situation? can please anybody tell me when to use one of them inside launch
?louiscad
11/01/2018, 8:24 AMwithContext
should suit most of the use cases also.Felix
11/01/2018, 10:16 AMasync
if you want to build and start a new coroutine, to run a parallel operation, obtaining a Deferred
to represent its result. You'll need a CoroutineScope
for it.
2) Use withContext
if you need to run code with a different context (e.g. with a new element added to the current context).
3) Use coroutineScope
if you need to build and start a set of coroutines and synchronise with their completion.Vsevolod Tolstopyatov [JB]
11/01/2018, 11:46 AMKulwinder Singh
11/02/2018, 6:01 AMcoroutineScope
like inside launch
why do we have to wrap two async tasks with coroutineScope
even if launch
is scoped to Activity lifecycleVsevolod Tolstopyatov [JB]
11/02/2018, 8:10 AMwhy do we have to wrap two async tasks withyou don’t have 🙂 Why do you think it is necessary?even ifcoroutineScope
is scoped to Activity lifecyclelaunch
Kulwinder Singh
11/02/2018, 8:49 AMasync
coroutines are running inside a suspending function
then it is best to wrap 2 async
with coroutineScope
because if 1 async
stoped with exception then second async
will stop, otherwise if we don't wrap it inside coroutineScope
then if 1 async
failed with exception then it will not stop second async
. But my question is that function is already called from launch
which is scoped to Activity
or Fragment
lifecycle ( e.g. uiScope.launch{ performTwoParallelTask() }
) then inside that function (eg -performTwoParallelTask
) why do we have coroutineScope
? [sorry if i'm unable to explain properly for my bad english]Felix
11/02/2018, 10:28 PMlaunch
or an async
. If inside a launch
block, then the receiver is a CoroutineScope
so you can just call launch
or async
. However when deeply nested inside suspend
functions, this
may not be a scope. A way to get one is via the coroutineScope
.