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

tseisel

01/27/2020, 3:07 PM
What's the purpose of
Dispatchers.Unconfined
? What kind of use-case does it solve ?
z

Zach Klippenstein (he/him) [MOD]

01/27/2020, 6:01 PM
I think mainly as an optimization: it saves the coroutine runtime from having to dispatch to a different thread if the coroutine doesn’t care what thread it’s executing on. It also has the nice property, when integrating with non-coroutine APIs like RxJava, that any call “into” the coroutines world (e.g., `offer`ing to a channel) will complete “synchronously”. So if your channel offer allows some coroutine to resume, calculate some values, and re-emit them back to RxJava, then that emission will happen before the
offer
returns. The
Main.immediate
dispatcher on Android has similar behavior, which makes it easier to reason about changes to the UI.
👍 1
r

rocketraman

01/28/2020, 3:35 AM
The docs here (https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-unconfined.html) specify another use case:
Nested coroutines launched in this dispatcher form an event-loop to avoid stack overflows.
As per the same docs, for the optimization of preventing initial dispatch, you don't need Unconfined... you can also do
launch
or
async
and specify
CoroutineStart.UNDISPATCHED
.
7 Views