launch Coroutine in Kotlin
Introduction
launch Coroutine is a fundamental concept every Kotlin developer should understand. Coroutines let you write asynchronous code that reads like synchronous code, without blocking threads or nesting callbacks.
Launch starts a new coroutine without returning result. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- launch starts a new coroutine without returning result.
- It is used for fire-and-forget tasks.
- Returns Job handle for cancellation and waiting.
Syntax
launch { ... }launch Coroutine in Kotlin Example Program in Kotlin
import kotlinx.coroutines.*
fun main(args: Array<String>) = runBlocking {
launch {
repeat(3) {
println("Task $it")
delay(50)
}
}
delay(200)
}Sample Output
Task 0
Task 1
Task 2When to use
Use coroutines for network requests, database queries, or any work that would block the main thread if done synchronously.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
launch {shows coroutine-based concurrency — work runs without blocking the calling thread. -
The
println("Task $it")statement writes a line to the console — this produces part of the sample output below. -
Launch starts a new coroutine without returning result.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
Common Mistakes
Key Points
- launch starts a new coroutine without returning result.
- It is used for fire-and-forget tasks.
- Returns Job handle for cancellation and waiting.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Add the
kotlinx-coroutines-coredependency when running coroutine examples outside Android or IntelliJ. - Semicolons at the end of statements are optional in Kotlin.