Kotlin
Summary - Coroutine basics
Combine launch, suspend and async/await to write a parallel downloader.
Summary - Coroutine basics
In this group you learned the coroutine basics. A coroutine is a lightweight thread that can be suspended. launch starts a resultless coroutine, async starts a resultful one. suspend functions wait without blocking the thread.
runBlocking bridges the blocking world to the suspending world; it is used in main and tests. async/await brings parallel computation with synchronous-looking code. Each tool works inside structured concurrency; it prevents resource leaks and keeps code clean.
Choosing the right tool
Pick the tool for the job: launch for resultless start, async/await for resultful parallel work. Functions that need to wait are written as suspend. Use the runBlocking bridge in main or tests.
Structured concurrency binds every coroutine to a scope; child coroutines finish before the scope ends. This prevents resource leaks without explicit wait calls. Separating parallel and sequential work correctly yields both performance and deterministic output.
Exercise Combine suspend and async/await
Add import kotlinx.coroutines.*. Define suspend fun fetch(): Int { delay(100); return 5 }. Write fun main() = runBlocking; inside call val a = async { fetch() } and println(a.await()).
Show example solution
import kotlinx.coroutines.*
suspend fun fetch(): Int {
delay(100)
return 5
}
fun main() = runBlocking {
val a = async { fetch() }
println(a.await())
}
Exercise Greet with runBlocking and suspend
Add import kotlinx.coroutines.*. Define suspend fun greet(name: String): String { delay(100); return "Hello, $name" }. Write fun main() = runBlocking { println(greet("Alex")) }.
Show example solution
import kotlinx.coroutines.*
suspend fun greet(name: String): String {
delay(100)
return "Hello, $name"
}
fun main() = runBlocking {
println(greet("Alex"))
}
Test yourself
-
Which starts a resultless coroutine?
- async
- launch
- runBlocking
- await
Show answer
launch — launch starts fire-and-forget.
-
Match the coroutine tools
- launch
- Resultless start
- async/await
- Resultful start
- suspend
- Can pause
- runBlocking
- Bridge
Next lesson: Flow