Careeroza
withTimeout and withTimeoutOrNull
Two Timeout Functions
| Function | On timeout |
|---|---|
withTimeout(ms) { } | throws TimeoutCancellationException |
withTimeoutOrNull(ms) { } | returns null |
Example
Example
import kotlinx.coroutines.*
suspend fun fetchQuote(ms: Long): String {
delay(ms)
return "RELIANCE: 2941.50"
}
fun main(): Unit = runBlocking {
val fast = withTimeoutOrNull(300) { fetchQuote(100) }
println("Fast call: $fast")
val slow = withTimeoutOrNull(300) { fetchQuote(1000) }
println("Slow call: ${slow ?: "timed out, showing cached price"}")
try {
withTimeout(200) { fetchQuote(1000) }
} catch (e: TimeoutCancellationException) {
println("withTimeout threw: ${e.message}")
}
}Output
Fast call: RELIANCE: 2941.50 Slow call: timed out, showing cached price withTimeout threw: Timed out waiting for 200 ms
Tip: TimeoutCancellationException is a subclass of CancellationException. If you call withTimeout inside a launch and do not catch it, the coroutine is just silently cancelled. Prefer withTimeoutOrNull when you want a fallback.