Junior — Middle
How can you set a time limit for coroutine execution in your project?
sobes.tech AI
Answer from AI
To limit the execution time of coroutines in Kotlin, you can use the withTimeout or withTimeoutOrNull functions from the kotlinx.coroutines library. They allow you to set a maximum execution time for a block of code, and if the coroutine does not finish within this time, a TimeoutCancellationException will be thrown or null will be returned, respectively.
Example:
import kotlinx.coroutines.*
fun main() = runBlocking {
try {
withTimeout(1000L) { // limit of 1000 milliseconds
repeat(5) { i ->
println("Iteration $i")
delay(300L) // simulate work
}
}
} catch (e: TimeoutCancellationException) {
println("Execution time has expired")
}
}
Thus, you can control the duration of coroutine execution and prevent hangs or excessively long operations.