Kotlin Suspend Functions
A suspend function is a function that can pause its work and resume later without blocking a thread. The suspend keyword marks such a function at the start of its declaration.
A suspend function called twice
fetch pauses with delay and then returns a string built from its number. The two calls run one after the other, so the prints land in call order.
import kotlinx.coroutines.*
suspend fun fetch(id: Int): String {
delay(10)
return "data-$id"
}
fun main() {
runBlocking {
println(fetch(1))
println(fetch(2))
println("Sequential done")
}
}Prints around a delay
countdown prints a start line, pauses with delay, and prints a finish line. The caller prints its own line after the call returns.
import kotlinx.coroutines.*
suspend fun countdown() {
println("Start")
delay(10)
println("Finish")
}
fun main() {
runBlocking {
countdown()
println("Done")
}
}A suspend function calling another
loadGreeting is a suspend function, and it calls the suspend function loadName in its body. The greeting is built from the name that call returns.
import kotlinx.coroutines.*
suspend fun loadName(): String {
delay(10)
return "Ana"
}
suspend fun loadGreeting(): String {
val name = loadName()
return "Hello, " + name
}
fun main() {
runBlocking {
println(loadGreeting())
}
}Two calls and one total
fetchPrice returns the same price on each call. The two calls run in sequence, and their results add up to 50.
import kotlinx.coroutines.*
suspend fun fetchPrice(): Int {
delay(10)
return 25
}
fun main() {
runBlocking {
val total = fetchPrice() + fetchPrice()
println(total)
}
}Example
import kotlinx.coroutines.*
suspend fun fetchStep(name: String): String {
delay(10)
return "$name ready"
}
suspend fun fetchReport(): String {
val first = fetchStep("first")
val second = fetchStep("second")
return first + " and " + second
}
fun main() {
runBlocking {
println(fetchReport())
println(fetchStep("third"))
}
}Key points
- Write suspend before fun to declare a suspend function.
- delay pauses the current coroutine for a set number of milliseconds.
- A suspend function can be called from a coroutine or from another suspend function.
- A suspend function can call another suspend function directly in its body.
- Calls made one after another run in call order, and their results print in call order.
In this example, fetchReport calls fetchStep twice in sequence and joins the two results into one string. The main block prints that report first. It then calls fetchStep once more and prints third ready.
Note
The examples use a short delay of 10 milliseconds, so the pause is real and the programs stay quick.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Kotlin Playground
Exercise
From where can a suspend function be called?