0Pricing
Kotlin Academy · Lesson

withTimeout and withTimeoutOrNull

Limit execution time with timeout wrappers and handle TimeoutCancellationException.

Why Timeouts?

Coroutines can hang indefinitely on network or I/O. withTimeout cancels the block if it does not complete within the given milliseconds.

import kotlinx.coroutines.*
fun main() = runBlocking {
    try {
        withTimeout(200) {
            delay(1000)  // simulates slow network
            println("This never prints")
        }
    } catch (e: TimeoutCancellationException) {
        println("Timed out!")
    }
}

withTimeout Basics

withTimeout(millis) { ... } throws TimeoutCancellationException (a subclass of CancellationException) if the block exceeds the limit.

import kotlinx.coroutines.*
suspend fun fetchData(): String {
    delay(100)
    return "data"
}
fun main() = runBlocking {
    val result = withTimeout(500) {
        fetchData()
    }
    println(result) // data
}

All lessons in this course

  1. Cooperative Cancellation: isActive and ensureActive
  2. withTimeout and withTimeoutOrNull
  3. Cleanup with finally and NonCancellable
  4. Cancellation Propagation in Coroutine Hierarchies
← Back to Kotlin Academy