Kotlin

Coroutine Timeout with withTimeout

admin by @admin ADMIN
2d ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`withTimeout(ms) { ... }` cancels the inner coroutine if it doesn't finish in time and throws `TimeoutCancellationException`. `withTimeoutOrNull` returns null instead.
Kotlin
Raw
import kotlinx.coroutines.*

suspend fun slowCall(): String {
    delay(500)
    return "result"
}

fun main() = runBlocking {
    // Throwing version
    try {
        val res = withTimeout(200) { slowCall() }
        println(res)
    } catch (e: TimeoutCancellationException) {
        println("timed out: ${e.message}")
    }

    // Null-returning version — cleaner for "optional" calls
    val maybe: String? = withTimeoutOrNull(200) { slowCall() }
    println("got: $maybe")          // null

    // Mix with retry logic
    val data = withTimeoutOrNull(1000) { slowCall() } ?: "default"
    println(data)
}
Tags

Save your own code snippets

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