0
votes

I am new to Kotlin coroutines and trying to understand its concept. I tested below code, all I wanted that last print statement should print before delay but I couldn't achieve that. I tried Dispatcher.IO in runblocking with assumption that it will run asynchronously but still no benefit.

fun main() {

println(Thread.currentThread().name)

runBlocking(Dispatchers.IO) {
    println("first "+Thread.currentThread().name)
    kotlinx.coroutines.delay(3000)
    println("second "+Thread.currentThread().name)
}
println("last "+Thread.currentThread().name)

}

output:

main

first DefaultDispatcher-worker-1

second DefaultDispatcher-worker-1

last main

1

1 Answers

0
votes

runBlocking will finish before going to the next line.. but in that block you can run a launch(Dispatched.IO){} block

println(Thread.currentThread().name)

runBlocking() {
    launch(Dispatchers.IO){
        println("first "+Thread.currentThread().name)
        kotlinx.coroutines.delay(3000)
        println("second "+Thread.currentThread().name)
    }
    println("still in blocking (runs at the same time as coroutines)"+Thread.currentThread().name)
}
println("last (runs after al coroutines are finsihed)"+Thread.currentThread().name)