I have tried reading various tutorials and pages on Kotlin coroutines and even though it kind of makes sense to me, I still don't feel it has clicked and I dont feel ready to jump on writing async non-blocking code with coroutines. I think what i am missing is a diagram or picture of what exactly happens and in what order when a piece of coroutine code executes. How does that code run at the thread level?
launch {
delay(1000)
println("World (${currentThread().name})")
}
println("Hello (${currentThread().name})")
sleep(1500)
My understanding is this. I am happy to be corrected or given a different example to further my understanding.
Line0: Code starts on main thread
Line1: Launches a new coroutine on a new thread (from forkjoin pool i suppose)
Line2: Suspending function so the coroutine suspends and returns the thread to the thread pool (hence being non-blocking)
Line5: Prints on the main thread
Line6: Blocks the main thread for 1.5s
Line3: The coroutine resumes execution on (not sure which thread here - same as the thread before suspension or can be a different thread?). The coroutines prints on that thread and finishes, hence returning the thread to the pool again.
Another question i have is how would the low-level execution change if i wrap the whole code around runBlocking { ... }