Coroutines
Coroutines
What are Coroutines?
Coroutines are Kotlin's approach to asynchronous, non-blocking programming. They are lightweight threads that can be suspended and resumed, allowing you to write asynchronous code that looks sequential and is easy to read.
Video Explanation

Setup
Add to your build.gradle.kts:
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
}
Your First Coroutine
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello,")
}
// Output:
// Hello,
// World!
Key Concepts
suspend Functions
Functions that can be paused and resumed. Must be called from a coroutine or another suspend function:
import kotlinx.coroutines.*
suspend fun fetchData(): String {
delay(2000L) // Simulate network delay
return "Data loaded!"
}
fun main() = runBlocking {
println("Fetching...")
val result = fetchData()
println(result)
}
Coroutine Builders
| Builder | Description |
|---|---|
runBlocking | Blocks the thread, for testing/main functions |
launch | Fire-and-forget, returns Job |
async | Returns Deferred<T> (future value) |
coroutineScope | Creates a scope, suspends until children finish |
launch — Fire and Forget
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
repeat(5) { i ->
println("Working... $i")
delay(500L)
}
}
println("Main continues")
job.join() // Wait for coroutine to finish
println("Done!")
}
async — Get a Result
import kotlinx.coroutines.*
suspend fun getTemperature(): Int {
delay(1000L)
return 25
}
suspend fun getHumidity(): Int {
delay(800L)
return 60
}
fun main() = runBlocking {
val tempDeferred = async { getTemperature() }
val humidDeferred = async { getHumidity() }
// Both run concurrently!
val temp = tempDeferred.await()
val humid = humidDeferred.await()
println("Temp: $temp°C, Humidity: $humid%")
}
Coroutine Scope
import kotlinx.coroutines.*
fun main() = runBlocking {
coroutineScope {
launch {
delay(200L)
println("Task 1 done")
}
launch {
delay(100L)
println("Task 2 done")
}
}
println("All tasks done")
}
// Output:
// Task 2 done
// Task 1 done
// All tasks done