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

Joan Colmenero

03/09/2020, 5:12 PM
Hey all can you guys explain me a little bit about EmptyCoroutineContext and ContinuationInterceptor I do not get it at all. I'm learning about coroutine contexts and I found these
z

Zach Klippenstein (he/him) [MOD]

03/09/2020, 5:15 PM
EmptyCoroutineContext
is a
CoroutineContext
that doesn’t have any elements. It’s an “identity” value for addition (
EmptyCoroutineContext + someOtherContext == someOtherContext
). It’s useful as a default value for context parameters.
ContinuationInterceptor
is something that can wrap every
Continuation
generated by the language within a particular
CoroutineContext
. It is how
CoroutineDispatcher
is implemented: whenever a
Continuation
is generated,
CoroutineDispatcher
wraps that continuation one that will “post” the original continuation on the correct thread pool. It’s a pretty low-level tool, probably not something you ever need to implement directly.
z

zak.taccardi

03/09/2020, 5:44 PM
What are reasons to use
EmptyCoroutineContext
over
Dispatchers.Unconfined
?
z

Zach Klippenstein (he/him) [MOD]

03/09/2020, 5:49 PM
They’re completely different. If the context is
EmptyCoroutineContext
, that means no dispatcher is specified, so when launching a new coroutine, the runtime will pick the default dispatcher (
Dispatchers.Default
). If the context contains
Dispatchers.Unconfined
, then it’s the same as specifying any other dispatcher in the context – new coroutines will use that dispatcher. When adding to another context,
EmptyCoroutineContext
has no effect whereas
Dispatchers.Unconfined
will override the dispatcher:
Copy code
(myContext + EmptyCoroutineContext)[ContinuationInterceptor] == myContext[ContinuationInterceptor]

(myContext + Dispatchers.Unconfined)[ContinuationInterceptor] == Dispatchers.Unconfined
👍 1
z

zak.taccardi

03/09/2020, 5:53 PM
Do you ever use
Dispatchers.Unconfined
?
I guess I’m trying to pin down use cases
for testing, I simply use the
CoroutineScope
from
runBlocking { }
or
runBlockingTest { }
and in prod code, all dispatchers are injected
z

Zach Klippenstein (he/him) [MOD]

03/09/2020, 5:56 PM
I’ve used
Unconfined
for “wiring” coroutines – coroutines that just shuffle data between other communication mechanisms – because it doesn’t make sense to waste time hopping around threads just to make thread-safe calls.
j

Joan Colmenero

03/09/2020, 6:51 PM
Thanks for yout answer @Zach Klippenstein (he/him) [MOD] but what's the purpose to use these?
z

Zach Klippenstein (he/him) [MOD]

03/09/2020, 6:52 PM
`EmptyCoroutineContext`:
It’s useful as a default value for context parameters.
`ContinuationInterceptor`:
It’s a pretty low-level tool, probably not something you ever need to implement directly.
👍 2
4 Views