Kotlin Coroutines
Apps constantly wait: for a network response, a database query, a file to load. If the program simply blocks while waiting, a phone's UI freezes and a server wastes threads. Coroutines are Kotlin's solution: functions that can suspend — pause without blocking a thread — and resume later, while your code still reads top to bottom like ordinary sequential code.
Coroutines live in the official kotlinx.coroutines library. In a Gradle project you add org.jetbrains.kotlinx:kotlinx-coroutines-core; on ExcelTAD it's already available, so the examples below run for real.
Key ideas
| Concept | What it is |
|---|---|
suspend fun |
a function that may pause; can only be called from a coroutine or another suspend function |
runBlocking { } |
starts a coroutine and blocks the current thread until it finishes (for main and tests) |
launch { } |
starts a coroutine that runs "in the background" and returns a Job |
async { } |
starts a coroutine that produces a value; get it with await() |
delay(ms) |
suspends for a while without blocking the thread (unlike Thread.sleep) |
CoroutineScope |
owns coroutines; when it ends or is cancelled, its children are too |
Your first coroutine
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(100)
println("World!")
}
println("Hello,")
}Hello,
World!
launch starts a new coroutine and returns immediately, so Hello, is printed first. The launched coroutine suspends in delay, then prints World!. runBlocking waits for all its child coroutines before main ends.
Suspend functions
Mark a function suspend to call other suspending functions inside it. Here two "downloads" run concurrently in one thread:
import kotlinx.coroutines.*
suspend fun download(name: String, ms: Long): String {
println("Start $name")
delay(ms) // pretend to wait for the network
println("Done $name")
return "$name.dat"
}
fun main() = runBlocking {
val job1 = launch { download("photos", 300) }
val job2 = launch { download("music", 100) }
joinAll(job1, job2)
println("All downloads finished")
}Start photos
Start music
Done music
Done photos
All downloads finished
Both downloads started immediately; the shorter one finished first. In total this takes about 300 ms, not 400 ms.
async and await
Use async when you need a result. It returns a Deferred<T>; await() suspends until the value is ready:
import kotlinx.coroutines.*
suspend fun fetchPrice(item: String): Double {
delay(200)
return when (item) {
"book" -> 12.5
"pen" -> 1.2
else -> 0.0
}
}
fun main() = runBlocking {
val book = async { fetchPrice("book") }
val pen = async { fetchPrice("pen") }
println("Fetching prices in parallel...")
val total = book.await() + pen.await()
println("Total: $total")
}Fetching prices in parallel...
Total: 13.7
Structured concurrency
Coroutines are always started inside a scope. A parent waits for its children, and if one child fails, the others are cancelled — so coroutines can't leak. coroutineScope { } creates such a scope inside a suspend function:
import kotlinx.coroutines.*
suspend fun loadDashboard(): List<String> = coroutineScope {
val user = async { delay(150); "user: kim" }
val news = async { delay(100); "news: 3 items" }
val weather = async { delay(50); "weather: sunny" }
listOf(user.await(), news.await(), weather.await())
}
fun main() = runBlocking {
val parts = loadDashboard()
parts.forEach { println(it) }
}user: kim
news: 3 items
weather: sunny
Cancellation and timeouts
A Job can be cancelled. delay and other suspending functions check for cancellation automatically. withTimeoutOrNull gives up after a time limit:
import kotlinx.coroutines.*
fun main() = runBlocking {
val ticker = launch {
repeat(10) { i ->
println("tick $i")
delay(100)
}
}
delay(250)
ticker.cancelAndJoin()
println("Ticker cancelled")
val result = withTimeoutOrNull(100) {
delay(500)
"slow answer"
}
println("Result: $result")
}tick 0
tick 1
tick 2
Ticker cancelled
Result: null
Flows: streams of values
A suspend function returns one value; a Flow emits many values over time. Flows are cold (nothing runs until you collect) and support operators like map and filter:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun countdown(from: Int): Flow<Int> = flow {
for (i in from downTo 1) {
delay(50)
emit(i)
}
}
fun main() = runBlocking {
countdown(5)
.filter { it % 2 == 1 }
.map { "T-minus $it" }
.collect { println(it) }
println("Liftoff!")
}T-minus 5
T-minus 3
T-minus 1
Liftoff!
Dispatchers
A dispatcher decides which thread(s) a coroutine runs on:
| Dispatcher | Use for |
|---|---|
Dispatchers.Main |
UI updates (Android, desktop) |
Dispatchers.IO |
blocking I/O: files, databases, network calls |
Dispatchers.Default |
CPU-heavy work like parsing or sorting |
Switch with withContext(Dispatchers.IO) { … } inside a suspend function. On Android, viewModelScope.launch { } starts coroutines that are cancelled automatically when the screen goes away.
Tip: Never call
Thread.sleepinside a coroutine — it blocks the whole thread. Usedelay. And avoidGlobalScope: always launch from a scope that has a clear lifetime.
Test yourself
What is the difference between delay(1000) and Thread.sleep(1000)?
- None
delaysuspends the coroutine without blocking the thread;sleepblocks the threaddelayis in secondssleeponly works on Android
Which builder should you use when a coroutine must return a value?
- launch
- async
- runBlocking only
- Thread
Where can a suspend function be called?
- Anywhere
- Only from a coroutine or another suspend function
- Only from main
- Only on Android