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)
}
Create a free account and build your private vault. Share publicly whenever you want.