What are coroutines?
- Kotlin course
- Intermediate
- Lesson 82/116
- 5 min
Learn the coroutine and async programming concept.
What are coroutines?
A coroutine is a lightweight thread that can suspend its work and resume later. A single thread can host thousands of coroutines with few resources; each coroutine takes a few hundred bytes.
Coroutines work with suspend functions: while waiting, they do not block the thread and let other work run. This replaces callback hell with clean code. The kotlinx.coroutines library provides tools like runBlocking, launch and async. In this lesson you will see the basic flow.
suspend and structured concurrency
A suspend function can pause and resume its work. While paused the thread is not blocked; other coroutines can run. delay is the simplest suspend function: it waits for a given time.
Structured concurrency ensures every coroutine has a scope. Child coroutines complete before the scope ends. This prevents resource leaks. runBlocking bridges the blocking world to the suspending world and waits for all coroutines inside.
Practice Run your first coroutine
Add import kotlinx.coroutines.*. Write fun main() = runBlocking { println("Hello coroutine") }. runBlocking opens a coroutine scope and blocks the main thread.
Starter code
import kotlinx.coroutines.*
// Define main with runBlocking and printSample solution
import kotlinx.coroutines.*
fun main() = runBlocking {
println("Hello coroutine")
}Expected output
Hello coroutine
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is a coroutine?
- A lightweight thread Correct answer
- A heavy thread
- A class type
- A data structure
Explanation: A coroutine is a lightweight thread that can be suspended.
2 Complete the delay import
import kotlinx.coroutines.____
suspend fun greet() { delay(100) }
import kotlinx.coroutines.delay
suspend fun greet() { delay(100) }
Explanation: delay is a suspend function.
3 Match the coroutine concepts
| Term | Meaning |
|---|---|
coroutine |
Lightweight task |
suspend |
Can pause |
delay |
Wait |
lightweight |
Few resources |