Is there an API that can accomplish `coroutineCont...
# coroutines
j
Is there an API that can accomplish
coroutineContext[CoroutineDispatcher]
without requiring
@OptIn(ExperimentalStdlibApi::class)
? CC: @Blake
s
Copy code
coroutineContext[ContinuationInterceptor] as? CoroutineDispatcher
gratitude thank you 1
j
Interesting, so it's only
AbstractCoroutineContextKey
, which
CoroutineDispatcher
implements, that's marked
ExperimentalStdlibApi
. But
CoroutineContext.Key
is not a
ExperimentalStdlibApi
, even though
AbstractCoroutineContextKey
is the base class for
CoroutineContext.Key
. 🤔 What's the difference between these APIs? And why is one experimental, and the other not?
plus1 1
s
It comes down to the idea of "polymorphic" context elements. The base type for all continuation interceptors, including dispatchers, is
ContinuationInterceptor
, and that's just a regular coroutine context element with a regular key. Nothing experimental or unexpected. A
CoroutineDispatcher
is a subtype of
ContinuationInterceptor
. So when we write
coroutineContext[CoroutineDispatcher]
, we're looking not just for a
ContinuationInterceptor
, but for a specific subtype of interceptor. That means
CoroutineDispatcher.Key
is a special type of key, sort of like a "sub-key" of
ContinuationInterceptor.Key
. I guess the exact specifics of what this means and how it should work are the bit that's experimental.
j
Thanks, this makes more sense now. I asked about the API being experimental a while back. I'm curious about some of those ways it's "easy to get wrong". To me, it seems less intuitive if you composed a
CoroutineContext
with a
CoroutineDispatcher
, but then can't decompose it using the same type. Rather, you have to identify the supertype that implements
CoroutineContext.Key
directly and cast it, obfuscating the code's intent as well.