What’s the difference between `coroutineScope` and...
# coroutines
v
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
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
coroutineScope
==
withContext(EmptyCoroutineContext)
coroutineScope
!=
withContext(Dispatchers.Default)
since the former inherits the dispatcher, while the latter replaces it with
Dispatchers.Default
.
o
e
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
hmm, okay
e
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
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
@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
@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
@Viktor Qvarfordt Yes,
suspend fun main()
runs on a dispatcher, and it's the default one, as one can expect.
259 Views