withTimeout

suspend fun <T> withTimeout(
    time: Int,
    block: suspend CoroutineScope.() -> T
): T
(source)

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

The code that is executing inside the block is cancelled on timeout and the active or next invocation of cancellable suspending function inside the block throws TimeoutCancellationException. Even if the code in the block suppresses TimeoutCancellationException, it is still thrown by withTimeout invocation.

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

This function delegates to Delay.invokeOnTimeout if the context CoroutineDispatcher implements Delay interface, otherwise it tracks time using a built-in single-threaded scheduled executor service.

Parameters

time - timeout time in milliseconds.

suspend fun <T> withTimeout(
    time: Long,
    unit: TimeUnit = TimeUnit.MILLISECONDS,
    block: suspend CoroutineScope.() -> T
): T
(source)

Platform and version requirements: JVM

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

The code that is executing inside the block is cancelled on timeout and the active or next invocation of cancellable suspending function inside the block throws TimeoutCancellationException. Even if the code in the block suppresses TimeoutCancellationException, it is still thrown by withTimeout invocation.

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

This function delegates to Delay.invokeOnTimeout if the context CoroutineDispatcher implements Delay interface, otherwise it tracks time using a built-in single-threaded scheduled executor service.

Parameters

time - timeout time

unit - timeout unit (milliseconds by default)