Hey all can you guys explain me a little bit about...
# coroutines
j
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
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
What are reasons to use
EmptyCoroutineContext
over
Dispatchers.Unconfined
?
z
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
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
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
Thanks for yout answer @Zach Klippenstein (he/him) [MOD] but what's the purpose to use these?
z
`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