timeout

Returns a flow that will emit a TimeoutCancellationException if the upstream doesn't emit an item within the given time.

Example:

flow {
emit(1)
delay(100)
emit(2)
delay(100)
emit(3)
delay(1000)
emit(4)
}.timeout(100.milliseconds).catch { exception ->
if (exception is TimeoutCancellationException) {
// Catch the TimeoutCancellationException emitted above.
// Emit desired item on timeout.
emit(-1)
} else {
// Throw other exceptions.
throw exception
}
}.onEach {
delay(300) // This will not cause a timeout
}

produces the following emissions

1, 2, 3, -1

Note that delaying on the downstream doesn't trigger the timeout.

Parameters

timeout

Timeout duration. If non-positive, the flow is timed out immediately