According to the documentation, a delay suspends a coroutine but doesn't block a thread:
Delay is a special suspending function. It suspends the coroutine for a specific time. Suspending a coroutine does not block the underlying thread, but allows other coroutines to run and use the underlying thread for their code.
However when running this code:
fun main() {
println("1")
GlobalScope.launch {
doSomething()
delay(1000L)
println("3")
}
GlobalScope.launch {
delay(1000L)
println("4")
}
println("5")
}
suspend fun doSomething() {
delay(500L)
println("2")
delay(1000L)
}
the output given is:
1
5
2
4
3
According to my understanding, it should have shown 1 5 4 2 3.
That's because doSomething() is being called in the first coroutine and so the delay is more as compared to the second coroutine and the second coroutine is called asynchronously. Where is my misunderstanding?
Also with this piece of code, both the values are printed together after 2 seconds:
fun main() {
GlobalScope.launch {
val value1 = doSomething1()
val value2 = doSomething2()
println(value1)
println(value2)
}
}
suspend fun doSomething1(): String {
delay(1000L)
return "This is the answer1"
}
suspend fun doSomething2(): String {
delay(1000L)
return "This is the answer2"
}
Why is this?