Unconfined dispatcher for performing coroutines

In what "borderline" cases can it be used Unconfined dispatcher to perform korutin?

Unconfined dispatcher is an advanced mechanism that can be helpful in certain corner cases where dispatching of coroutine for its execution later is not needed or produces undesirable side-effects, because some operation in a coroutine must be performed right away.

As far as I understand it, it translates like this: "Unconfined dispatcher is an advanced mechanism that can be useful in some cases where you don't need to send the coroutine to execute it later, or it creates unwanted side effects because some operation in the coroutine needs to be performed right now. "

And do I understand correctly that this means that this dispatcher should be used in cases where it is not necessary to postpone the execution of the coroutine using delay or similar mechanisms? And why is it further written that Unconfined dispatcher should not be used in general code?

And I also don't understand how the suspending function defines a thread in which, after it is called, the execution of the coroutine defined with Dispatchers.Unconfined resumes. An example given in the same article:

fun main() = runBlocking<Unit> {
    launch(Dispatchers.Unconfined) { // not confined -- will work with main thread
        println("Unconfined      : I'm working in thread ${Thread.currentThread().name}")
        delay(500)
        println("Unconfined      : After delay in thread ${Thread.currentThread().name}")
    }  
}

Output:

Unconfined      : I'm working in thread main
Unconfined      : After delay in thread kotlinx.coroutines.DefaultExecutor

How did the function delay() define the thread for the next coroutine execution after it as kotlinx.coroutines.DefaultExecutor?

Author: Ksenia, 2018-11-11

1 answers

Did you read everything there?

The Dispatchers.Unconfined coroutine dispatcher starts coroutine in the caller thread, but only until the first suspension point. After suspension it resumes in the thread that is fully determined by the suspending function that was invoked. Unconfined dispatcher is appropriate when coroutine does not consume CPU time nor updates any shared data (like UI) that is confined to a specific thread.

In other words, for tasks that do not it requires resources and does not matter where it is executed. I understand that it was invented to save on switching.

 1
Author: Eugene Krivenja, 2018-11-14 16:16:08