Tushar
09/10/2024, 3:11 PMfun 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?Michael Krussel
09/10/2024, 5:16 PMrunBlocking
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.Tushar
09/10/2024, 5:28 PM