Kotlin / kotlinx.coroutines

Library support for Kotlin coroutines
Apache License 2.0
12.94k stars 1.84k forks source link

TimeoutCancellationException inconsistently bubbled up #3716

Open thadcodes opened 1 year ago

thadcodes commented 1 year ago

Describe the bug

When a TimeoutCancelationException occurs inside a flow it gets thrown and can be caught in the catch block. But if it is thrown in a flow that is attached with a flatMap the exception is ignored/swallowed.

Provide a Reproducer

The code at the bottom of this section running in https://play.kotlinlang.org/ using version kotlin 1.8.20 emits the following

This should never execute
Found error java.lang.RuntimeException
Found error kotlinx.coroutines.TimeoutCancellationException: Timed out immediately

but it should emit the following:

Found error kotlinx.coroutines.TimeoutCancellationException: Timed out immediately
Found error java.lang.RuntimeException
Found error kotlinx.coroutines.TimeoutCancellationException: Timed out immediately
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.*

@kotlinx.coroutines.ExperimentalCoroutinesApi
fun main() = runBlocking {
    runTest {
        withTimeout(0L) {
                // Do nothing this will not execute
            }
    }

    runTest {
        throw RuntimeException()
    }
    flow<Boolean> {
        emit(true)
        //throw RuntimeException()
        withTimeout(0L) {
            // Do nothing this will not execute
        }
    }

    .onCompletion {
        if(it == null) println("This should never execute")
    }
    .catch { println("Found error $it") }
    .collect()
}

suspend fun runTest(block: suspend FlowCollector<Boolean>.() -> Unit) = flow {
        emit(true)
    }.flatMapLatest {
        flow<Boolean> {
            block()                      
        }
    }.onCompletion {
        if(it == null) println("This should never execute")
    }
    .catch { println("Found error $it") }
    .collect()
dkhalanskyjb commented 1 year ago

Related: https://github.com/Kotlin/kotlinx.coroutines/issues/1374