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
}