Viktor Qvarfordt
05/16/2019, 7:53 PMcoroutineScope
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
?octylFractal
05/16/2019, 7:57 PMwithContext
does not create a new Job -- so all started coroutines are children of the parent Scope, instead of a new scope with coroutineScope
elizarov
05/16/2019, 7:59 PMcoroutineScope
== withContext(EmptyCoroutineContext)
elizarov
05/16/2019, 7:59 PMcoroutineScope
!= withContext(Dispatchers.Default)
since the former inherits the dispatcher, while the latter replaces it with Dispatchers.Default
.octylFractal
05/16/2019, 7:59 PMwithContext(Job())
? I don't see withContext
as specifying `Job`: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-context.html
but coroutineScope
does: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.htmlelizarov
05/16/2019, 8:00 PMwithContext(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)octylFractal
05/16/2019, 8:01 PMelizarov
05/16/2019, 8:02 PMsuspends 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.htmlelizarov
05/16/2019, 8:03 PMEvery 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.
Viktor Qvarfordt
05/16/2019, 8:18 PMwithContext(Dispatchers.Default)
or coroutineScope
runs the suspend block on a thread pool of numCpus number of threads?louiscad
05/16/2019, 8:47 PMcoroutineScope { … }
doesn't change the dispatcher. If the current coroutineContext
is Dispatchers.Main
for example, it will stay here, on that single thread backed dispatcher.Viktor Qvarfordt
05/16/2019, 8:51 PMsuspend fun main() = coroutineScope { … }
which does use Dispatcher.Default
. It uses Dispatchers.Default
rather than Dispatchers.Main
because it is the outer-most block?louiscad
05/17/2019, 12:02 AMsuspend fun main()
runs on a dispatcher, and it's the default one, as one can expect.