Skip to content

Commit c675e3f

Browse files
3789: Update flow.timeout example to re-throw (#3801)
Fixes #3789 Co-authored-by: Vsevolod Tolstopyatov <[email protected]>
1 parent 9b06a69 commit c675e3f

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

kotlinx-coroutines-core/common/src/flow/operators/Delay.kt

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ public fun <T> Flow<T>.debounce(timeout: (T) -> Duration): Flow<T> =
203203
timeout(emittedItem).toDelayMillis()
204204
}
205205

206-
private fun <T> Flow<T>.debounceInternal(timeoutMillisSelector: (T) -> Long) : Flow<T> =
206+
private fun <T> Flow<T>.debounceInternal(timeoutMillisSelector: (T) -> Long): Flow<T> =
207207
scopedFlow { downstream ->
208208
// Produce the values using the default (rendezvous) channel
209209
val values = produce {
@@ -306,7 +306,10 @@ public fun <T> Flow<T>.sample(periodMillis: Long): Flow<T> {
306306
/*
307307
* TODO this design (and design of the corresponding operator) depends on #540
308308
*/
309-
internal fun CoroutineScope.fixedPeriodTicker(delayMillis: Long, initialDelayMillis: Long = delayMillis): ReceiveChannel<Unit> {
309+
internal fun CoroutineScope.fixedPeriodTicker(
310+
delayMillis: Long,
311+
initialDelayMillis: Long = delayMillis
312+
): ReceiveChannel<Unit> {
310313
require(delayMillis >= 0) { "Expected non-negative delay, but has $delayMillis ms" }
311314
require(initialDelayMillis >= 0) { "Expected non-negative initial delay, but has $initialDelayMillis ms" }
312315
return produce(capacity = 0) {
@@ -359,8 +362,15 @@ public fun <T> Flow<T>.sample(period: Duration): Flow<T> = sample(period.toDelay
359362
* emit(3)
360363
* delay(1000)
361364
* emit(4)
362-
* }.timeout(100.milliseconds).catch {
363-
* emit(-1) // Item to emit on timeout
365+
* }.timeout(100.milliseconds).catch { exception ->
366+
* if (exception is TimeoutCancellationException) {
367+
* // Catch the TimeoutCancellationException emitted above.
368+
* // Emit desired item on timeout.
369+
* emit(-1)
370+
* } else {
371+
* // Throw other exceptions.
372+
* throw exception
373+
* }
364374
* }.onEach {
365375
* delay(300) // This will not cause a timeout
366376
* }

kotlinx-coroutines-core/jvm/test/examples/example-timeout-duration-01.kt

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,15 @@ flow {
1919
emit(3)
2020
delay(1000)
2121
emit(4)
22-
}.timeout(100.milliseconds).catch {
23-
emit(-1) // Item to emit on timeout
22+
}.timeout(100.milliseconds).catch { exception ->
23+
if (exception is TimeoutCancellationException) {
24+
// Catch the TimeoutCancellationException emitted above.
25+
// Emit desired item on timeout.
26+
emit(-1)
27+
} else {
28+
// Throw other exceptions.
29+
throw exception
30+
}
2431
}.onEach {
2532
delay(300) // This will not cause a timeout
2633
}

0 commit comments

Comments
 (0)