0
0
Kotlinprogramming~5 mins

Launch coroutine builder in Kotlin

Choose your learning style9 modes available
Introduction

The launch coroutine builder lets you start a new task that runs in the background without blocking the main program. It helps you do many things at once easily.

When you want to run a task that does not return a result and can run alongside other tasks.
When you need to perform background work like fetching data or waiting for a timer without freezing the app.
When you want to start a task that can be cancelled later if needed.
When you want to keep your app responsive by running long tasks outside the main thread.
Syntax
Kotlin
launch(context) {
    // code to run in coroutine
}

launch starts a new coroutine immediately.

The context is optional and defines where the coroutine runs (like on the main thread or background).

Examples
Starts a coroutine on the default dispatcher and prints a message.
Kotlin
launch {
    println("Hello from coroutine!")
}
Starts a coroutine on a background thread for input/output tasks.
Kotlin
launch(Dispatchers.IO) {
    // Run blocking IO task here
}
Starts a coroutine that can be cancelled before it finishes.
Kotlin
val job = launch {
    delay(1000L)
    println("Task done")
}

job.cancel()
Sample Program

This program starts a coroutine that waits half a second and then prints "World!" while the main coroutine prints "Hello," immediately. The delay at the end keeps the program running so we see both messages.

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        delay(500L)
        println("World!")
    }
    println("Hello,")
    delay(1000L) // Wait to keep JVM alive
}
OutputSuccess
Important Notes

launch returns a Job which you can use to cancel or check the coroutine.

Coroutines started with launch do not return a result. Use async if you need a result.

Always use runBlocking or another coroutine scope to keep the program alive when testing coroutines in main.

Summary

launch starts a new coroutine that runs independently.

It is useful for background tasks that do not return a value.

You can control and cancel coroutines using the Job returned by launch.