I started looking into Coroutines a few days ago. I understand a little bit, but then I saw some lines of code that raised some questions:
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
println("in sub coroutine ${Thread.currentThread().name}")
}
println("before coroutine in main ${Thread.currentThread().name}")
withContext(Dispatchers.IO) {
println("hello from coroutine ${Thread.currentThread().name}")
delay(1500)
println("hello from coutoutine after delay ${Thread.currentThread().name}")
}
println("after coroutine in main ${Thread.currentThread().name}")
}
The output is:
before coroutine in main main @coroutine#1
in sub coroutine main @coroutine#2
hello from coroutine DefaultDispatcher-worker-1 @coroutine#1
hello from coutoutine after delay DefaultDispatcher-worker-1 @coroutine#1
after coroutine in main main @coroutine#1
From my understanding, launch creates a new coroutine on the worker thread, thus any normal function on main thread is executed before the launch is completed. If so, I am a bit confused why the withContext code runs before the launch code. Can someone explain?
withContext(Dispatchers.IO)suspends the main thread giving the code insidelaunchblock the chance to be executed, while the code insidewithContextblock runs concurrently. Actually according to your output,launchblock gets executed beforewithContextblock. The last line gets executed afterwithContextblock because the main thread resumes execution as soon aswithContextfinishes. - Glenn Sandovallaunchblock andwithContextblock run concurrently so that behavior can be expected. Although you shouldn't expectwithContextto finish beforelaunchfinishes because of thedelaycall. - Glenn Sandoval