How do I write a suspend function in Kotlin?

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 fun to define one.
  • A suspend function can call other suspend functions.
  • It must be called from:
    • another suspend function, or
    • a coroutine scope such as runBlocking, launch, or async.

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
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.