How do I launch a coroutine in Kotlin using launch and runBlocking?

In Kotlin, you can use runBlocking to start a coroutine scope that blocks the current thread until its coroutines finish, and launch to start a new coroutine inside that scope.

import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    launch {
        println("Coroutine is running")
    }

    println("Main coroutine continues")
}

Output may look like:

Main coroutine continues
Coroutine is running

runBlocking creates a coroutine and blocks the current thread until all child coroutines complete.

launch starts a new coroutine that runs concurrently with the rest of the code inside the runBlocking scope.

A slightly clearer example:

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    launch {
        delay(1000)
        println("World!")
    }

    println("Hello")
}

Output:

Hello
World!

Here:

  • runBlocking { ... } starts a blocking coroutine scope.
  • launch { ... } starts a child coroutine.
  • delay(1000) suspends the coroutine for 1 second without blocking the thread.
  • runBlocking waits until the launched coroutine finishes before main exits.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.