In android i am launching coroutine using `launch`...
# coroutines
k
In android i am launching coroutine using
launch
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
?
l
The documentation explains it well, you should read it.
withContext
should suit most of the use cases also.
f
1) Use
async
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.
👍 2
v
Have you read documentation to that methods? If yes and it was not helpful, could you please file an issue on github?
k
I can't say that documentation is bad because there are some changes in recent versions of Coroutines like scoped concurrency and also CoroutineContext and CoroutineScope is new to me thats why i was confused little bit ,mainly i'm confused with
coroutineScope
like inside
launch
why do we have to wrap two async tasks with
coroutineScope
even if
launch
is scoped to Activity lifecycle
v
why do we have to wrap two async tasks with
coroutineScope
even if
launch
is scoped to Activity lifecycle
you don’t have 🙂 Why do you think it is necessary?
k
I have seen chris banes talk [

https://www.youtube.com/watch?v=P7ov_r1JZ1g&t=998s

] from KotlinConf 2018 , where he explains that When 2
async
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]
f
First of all, you always need a scope for a
launch
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
.