<https://kotlinlang.org/docs/coroutines-and-channe...
# getting-started
t
https://kotlinlang.org/docs/coroutines-and-channels.html#starting-a-new-coroutine i was reading this part of kotlin documentation on coroutine to deepen my understanding, came across a line "When the computation is ready to be continued, it is returned to a thread (not necessarily the same one)." i have few doubt regarding it 1. If we simply use launch without providing any dispatcher how come it creates a new thread, for instance i tried the below code found everything was blocked as expected, to verify the claim of above line.
Copy code
fun main(): Unit = runBlocking{
    launch{
        (1..5).onEach {
            launch {
                mimicNetworkRequest(it)
            }
        }
    }
    println("mimicing main is busy..")
    Thread.sleep(5000)
    println("wokeUp back to work")
}
suspend fun mimicNetworkRequest(index: Int){
    println(" doing a network request $index ${Thread.currentThread().name} $CoroutineName")
     delay(2000)
    println("done $index ${Thread.currentThread().name} $CoroutineName")
}
2. Secondly if it doesn't creates a new thread what happens when the calling thread is busy somewhere else like in above code thread is sleeping, so does coroutine keeps waiting ? 3. On a single thread when many coroutines are ready to run, how the decision is made to choose one among them? does it follows similar context switching like OS does?
m
1. Launch without a dispatcher inherits the dispatcher from the parent. I don't know what
runBlocking
uses. 2. The coroutine stays suspended until the dispatcher can dispatch it. 3. I believe most of the dispatchers are fair and resuming is done in a FIFO order.
t
@Michael Krussel Thanks, i had a misconception that using dispatchers gets you a new thread overlooking the "Thread Pool"