In Kotlin, a suspend function is declared with the suspend modifier.
suspend fun fetchUser(): User {
// Can call other suspend functions here
return api.getUser()
}
A suspend function can pause without blocking the thread and later resume. It is commonly used with coroutines for asynchronous work.
Example:
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
suspend fun greetAfterDelay() {
delay(1000)
println("Hello after 1 second")
}
fun main() = runBlocking {
greetAfterDelay()
}
Key points:
- Use
suspend funto define one. - A suspend function can call other suspend functions.
- It must be called from:
- another
suspendfunction, or - a coroutine scope such as
runBlocking,launch, orasync.
- another
Example with return value:
suspend fun loadMessage(): String {
delay(500)
return "Loaded message"
}
fun main() = runBlocking {
val message = loadMessage()
println(message)
}
So the basic syntax is:
suspend fun functionName() {
// suspending work
}
