runBlocking. What will be printed when this code runs?import kotlinx.coroutines.* fun main() = runBlocking { launch { delay(100) println("Inside launch") } println("Before delay") delay(200) println("After delay") }
runBlocking waits for all child coroutines to complete before finishing.The runBlocking block waits for all launched coroutines inside it to finish. The launch coroutine delays 100ms before printing. Meanwhile, the main coroutine prints "Before delay", then delays 200ms, allowing the launched coroutine to complete and print "Inside launch" before finally printing "After delay".
import kotlinx.coroutines.* fun main() { runBlocking { launch { delay(100) println("Hello") } } println("Done") }
The runBlocking block waits for the launch coroutine to complete before exiting. The println("Done") is outside runBlocking and runs after it finishes. Since launch delays 100ms before printing "Hello", the output order is "Hello" then "Done".
runBlocking is used in Kotlin coroutines?runBlocking helps when calling suspend functions from normal code.runBlocking is designed to bridge blocking code and suspend functions by blocking the current thread until the coroutine inside completes. This allows calling suspend functions from regular code, such as main(), which is not a suspend function.
import kotlinx.coroutines.* fun main() = runBlocking { val job = launch { delay(1000) println("Task done") } job.cancel() println("Cancelled") }
The job.cancel() call cancels the launched coroutine immediately before it completes its delay and print. Therefore, "Task done" is never printed. The program prints "Cancelled" and ends normally.
import kotlinx.coroutines.* fun main() = runBlocking { val jobs = List(3) { i -> launch { delay(100L * i) println("Coroutine $i done") } } jobs.forEach { it.join() } println("All done") }
There are 3 launched coroutines, each printing "Coroutine 0 done", "Coroutine 1 done", and "Coroutine 2 done" after delays. After all join, the main coroutine prints "All done". So total lines printed are 4.