0
0
KotlinHow-ToBeginner · 3 min read

How to Use launch in Kotlin for Coroutines

In Kotlin, launch is used to start a new coroutine without blocking the current thread. It runs the coroutine concurrently and returns immediately, allowing you to perform asynchronous tasks simply inside a CoroutineScope.
📐

Syntax

The launch function is called on a CoroutineScope and takes a block of code to run asynchronously. It returns a Job that represents the coroutine.

  • CoroutineScope.launch { ... }: Starts a new coroutine.
  • The block inside launch contains the code to run concurrently.
  • The coroutine runs without blocking the current thread.
kotlin
CoroutineScope.launch {
    // code to run asynchronously
}
💻

Example

This example shows how to use launch inside the runBlocking scope to start a coroutine that prints a message after a delay. The main thread continues without waiting for the coroutine to finish immediately.

kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        delay(1000L)
        println("World!")
    }
    println("Hello,")
}
Output
Hello, World!
⚠️

Common Pitfalls

One common mistake is calling launch outside a CoroutineScope, which causes a compilation error. Another is forgetting that launch is asynchronous, so the program may finish before the coroutine runs unless you wait for it.

Always use launch inside a scope like runBlocking, GlobalScope, or a custom scope, and consider using join() on the returned Job to wait for completion if needed.

kotlin
import kotlinx.coroutines.*

fun main() {
    // Wrong: launch called outside CoroutineScope
    // launch { println("Hello") } // Error

    // Right: launch inside runBlocking scope
    runBlocking {
        val job = launch {
            delay(500L)
            println("Inside coroutine")
        }
        job.join() // Wait for coroutine to finish
    }
}
Output
Inside coroutine
📊

Quick Reference

FunctionDescription
launch { ... }Starts a new coroutine without blocking the current thread
runBlocking { ... }Creates a blocking coroutine scope for main or tests
job.join()Waits for the coroutine started by launch to complete
CoroutineScopeDefines the scope where coroutines run

Key Takeaways

Use launch inside a CoroutineScope to start asynchronous coroutines.
launch runs code concurrently without blocking the current thread.
Always call launch within a CoroutineScope like runBlocking or GlobalScope.
Use job.join() to wait for a launched coroutine to finish if needed.
launch returns a Job that can be used to manage the coroutine lifecycle.