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

Viktor Qvarfordt

05/16/2019, 7:53 PM
What’s the difference between
coroutineScope
and
withContext(Dispatchers.Default)
? They both launch a suspend block with context
Dispatchers.Default
. Is
withContext
the same as
coroutineScope { ... }.join()
? Is there a version of
withContext
that defaults to use
Dipsatchers.Default
similar to how
coroutineScope
uses
Dispatchers.Default
?
o

octylFractal

05/16/2019, 7:57 PM
withContext
does not create a new Job -- so all started coroutines are children of the parent Scope, instead of a new scope with
coroutineScope
e

elizarov

05/16/2019, 7:59 PM
coroutineScope
==
withContext(EmptyCoroutineContext)
coroutineScope
!=
withContext(Dispatchers.Default)
since the former inherits the dispatcher, while the latter replaces it with
Dispatchers.Default
.
o

octylFractal

05/16/2019, 7:59 PM
e

elizarov

05/16/2019, 8:00 PM
No.
withContext(Job())
is a weird thing that you should never do as it breaks structured concurrency (we should have forbidden it, but we cannot due to backwards compatibility)
o

octylFractal

05/16/2019, 8:01 PM
hmm, okay
e

elizarov

05/16/2019, 8:02 PM
Every function that accepts
suspends CoroutineScope.() -> T
as its parameter creates a Job, because that's the key part of the
CoroutineScope
intended usage. More details here: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html
Quote from there:
Every coroutine builder (like launch, async, etc) and every scoping function (like coroutineScope, withContext, etc) provides its own scope with its own Job instance into the inner block of code it runs. By convention, they all wait for all the coroutines inside their block to complete before completing themselves, thus enforcing the discipline of structured concurrency.
v

Viktor Qvarfordt

05/16/2019, 8:18 PM
Is it correct that creating a block with either
withContext(Dispatchers.Default)
or
coroutineScope
runs the suspend block on a thread pool of numCpus number of threads?
l

louiscad

05/16/2019, 8:47 PM
@Viktor Qvarfordt No,
coroutineScope { … }
doesn't change the dispatcher. If the current
coroutineContext
is
Dispatchers.Main
for example, it will stay here, on that single thread backed dispatcher.
v

Viktor Qvarfordt

05/16/2019, 8:51 PM
@louiscad Oh, I think I see now! I’m thinking of your example
suspend fun main() = coroutineScope { … }
which does use
Dispatcher.Default
. It uses
Dispatchers.Default
rather than
Dispatchers.Main
because it is the outer-most block?
l

louiscad

05/17/2019, 12:02 AM
@Viktor Qvarfordt Yes,
suspend fun main()
runs on a dispatcher, and it's the default one, as one can expect.
208 Views