https://kotlinlang.org logo
#coroutines
Title
# coroutines
k

Kulwinder Singh

11/01/2018, 8:18 AM
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

louiscad

11/01/2018, 8:24 AM
The documentation explains it well, you should read it.
withContext
should suit most of the use cases also.
f

Felix

11/01/2018, 10:16 AM
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

Vsevolod Tolstopyatov [JB]

11/01/2018, 11:46 AM
Have you read documentation to that methods? If yes and it was not helpful, could you please file an issue on github?
k

Kulwinder Singh

11/02/2018, 6:01 AM
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

Vsevolod Tolstopyatov [JB]

11/02/2018, 8:10 AM
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

Kulwinder Singh

11/02/2018, 8:49 AM
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

Felix

11/02/2018, 10:28 PM
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
.
3 Views