withTimeout

suspend fun <T> withTimeout(timeMillis: Long, block: suspend CoroutineScope.() -> T): T

Runs a given suspending block of code inside a coroutine with a specified timeout and throws a TimeoutCancellationException if the timeout was exceeded.

The code that is executing inside the block is cancelled on timeout and the active or next invocation of the cancellable suspending function inside the block throws a TimeoutCancellationException.

The sibling function that does not throw an exception on timeout is withTimeoutOrNull. Note that the timeout action can be specified for a select invocation with onTimeout clause.

The timeout event is asynchronous with respect to the code running in the block and may happen at any time, even right before the return from inside of the timeout block. Keep this in mind if you open or acquire some resource inside the block that needs closing or release outside of the block. See the Asynchronous timeout and resources[https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html#asynchronous-timeout-and-resources] section of the coroutines guide for details.

Implementation note: how the time is tracked exactly is an implementation detail of the context's CoroutineDispatcher.

Parameters

timeMillis

timeout time in milliseconds.

suspend fun <T> withTimeout(timeout: Duration, block: suspend CoroutineScope.() -> T): T

Runs a given suspending block of code inside a coroutine with the specified timeout and throws a TimeoutCancellationException if the timeout was exceeded.

The code that is executing inside the block is cancelled on timeout and the active or next invocation of the cancellable suspending function inside the block throws a TimeoutCancellationException.

The sibling function that does not throw an exception on timeout is withTimeoutOrNull. Note that the timeout action can be specified for a select invocation with onTimeout clause.

The timeout event is asynchronous with respect to the code running in the block and may happen at any time, even right before the return from inside of the timeout block. Keep this in mind if you open or acquire some resource inside the block that needs closing or release outside of the block. See the Asynchronous timeout and resources[https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html#asynchronous-timeout-and-resources] section of the coroutines guide for details.

Implementation note: how the time is tracked exactly is an implementation detail of the context's CoroutineDispatcher.