Skip to content

TimeoutCancellationException inconsistently bubbled up #3716

Open
@thadcodes

Description

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()

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions