Kotlin

Coroutines — suspend Function Basics

admin by @admin ADMIN
Jun 16, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`suspend fun` can be paused and resumed without blocking a thread. Call only from another `suspend` function or a coroutine builder (`launch`, `runBlocking`, `async`).
Kotlin
Raw
import kotlinx.coroutines.*

suspend fun fetchUser(id: Int): String {
    delay(100)                                  // non-blocking pause (vs Thread.sleep)
    return "User $id"
}

fun main() = runBlocking {                      // bridge from non-coroutine main
    println("starting at ${System.currentTimeMillis()}")
    val user = fetchUser(42)
    println(user)
    println("done at ${System.currentTimeMillis()}")
}

// Key points:
// • `suspend` is a marker on the function signature — the compiler rewrites
//   the body into a state machine that can pause at every `suspend` call.
// • A suspend function called from another suspend function is just a normal
//   sequential call; threads aren't tied up while waiting.
// • Use `Dispatchers.IO` / `Dispatchers.Default` (via withContext) to choose
//   what thread pool runs the work — see other snippets.
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.