runBlocking
- Kotlin course
- Intermediate
- Lesson 85/116
- 5 min
Learn coroutine main with runBlocking.
runBlocking
runBlocking is the bridge from the blocking world to the suspending world. It blocks the calling thread while running coroutines inside and does not return until they all finish. Example: fun main() = runBlocking { println(compute()) }.
runBlocking is especially useful in main and tests. In production code, where blocking coroutines is undesirable, an appropriate scope is preferred over runBlocking. But at an entry point or in a test it is the easiest way to call suspend functions. Using runBlocking in main is a common pattern.
Using runBlocking
Inside runBlocking suspend functions are called directly. Example: fun main() = runBlocking { val result = compute(); println("Result: $result") }. runBlocking does not return until compute finishes.
When multiple suspend functions are called sequentially each is awaited; the total time is the sum of waits. For parallel work use async; you will see it in the next lesson. runBlocking is mainly used as a bridge in main or in @Test methods.
Practice Call suspend with runBlocking
Add import kotlinx.coroutines.*. Define suspend fun compute(): Int { delay(100); return 10 }. Write fun main() = runBlocking { val result = compute(); println("Result: $result") }.
Starter code
import kotlinx.coroutines.*
// Define the compute suspend function: returns 10 after delay
// Call compute in runBlocking in main and printSample solution
import kotlinx.coroutines.*
suspend fun compute(): Int {
delay(100)
return 10
}
fun main() = runBlocking {
val result = compute()
println("Result: $result")
}Expected output
Result: 10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does runBlocking do?
- Does not start a coroutine
- Only calls suspend
- Never finishes
- Blocks the thread and runs coroutines Correct answer
Explanation: runBlocking blocks the thread while running coroutines.
2 Complete the runBlocking declaration
fun main() = ____ { println("Ready") }
fun main() = runBlocking { println("Ready") }
Explanation: runBlocking opens a scope in main.
3 Match the runBlocking concepts
| Term | Meaning |
|---|---|
runBlocking |
Thread blocks |
main() |
Entry point |
bridge |
Bridge |
test |
Common use |