Coroutine Introduction in Kotlin
On this page (12sections)
Introduction
Coroutine Introduction 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.
Coroutines provide lightweight concurrency for asynchronous code. 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
- Coroutines provide lightweight concurrency for asynchronous code.
- They simplify async programming compared to callback chains.
- Coroutine support is provided by kotlinx.coroutines library.
Syntax
import kotlinx.coroutines.*
Coroutine Introduction in Kotlin Example Program in Kotlin
import kotlinx.coroutines.*
fun main(args: Array<String>) = runBlocking {
println("Main starts")
launch {
delay(100)
println("Coroutine finished")
}
println("Main ends")
}
Sample Output
Main starts
Main ends
Coroutine finished
When 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. -
The
println("Main starts")statement writes a line to the console — this produces part of the sample output below. -
launch {shows coroutine-based concurrency — work runs without blocking the calling thread. -
The
println("Coroutine finished")statement writes a line to the console — this produces part of the sample output below. -
The
println("Main ends")statement writes a line to the console — this produces part of the sample output below. -
Coroutines provide lightweight concurrency for asynchronous code.
-
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
- Never block the main thread — use
suspendfunctions and appropriate dispatchers. - Scope coroutines with
coroutineScopeorsupervisorScopefor structured cancellation. - Use
delayinstead ofThread.sleepinside coroutines.
Common Mistakes
- Launching coroutines without a scope — leaks work after the UI is destroyed.
- Using
GlobalScopein application code instead of a lifecycle-aware scope. - Calling blocking APIs directly on
Dispatchers.Main.
Key Points
- Coroutines provide lightweight concurrency for asynchronous code.
- They simplify async programming compared to callback chains.
- Coroutine support is provided by kotlinx.coroutines library.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Add kotlinx-coroutines dependency in real projects.