Skip to content

TimeoutCancellationException is thrown inconsistently between flatMapConcat and flatMapLatest #3392

Open
@rossdanderson

Description

@rossdanderson

In the code below, the TimeoutCancellationException thrown by withTimeout is propagated as expected when using flatMapConcat, but not propagated when using flatMapLatest.
If withTimeout is replaced with check(false), the exception is propagated as expected in both.

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout

val flow = flowOf("A", "B")

runBlocking {
    var threw1 = false
    try {
        flow
            .flatMapConcat {
                callbackFlow<String> {
                    withTimeout(100) { delay(1000) }
                }
            }
            .collect()
    } catch (t: Throwable) {
        threw1 = true
        println("Error1 $t")
    }

    var threw2 = false
    try {
        flow
            .flatMapLatest {
                callbackFlow<String> {
                    withTimeout(100) { delay(1000) }
                }
            }
            .collect()
    } catch (t: Throwable) {
        threw2 = true
        println("Error2 $t")
    }

    if (!threw1) println("flatMapConcat did NOT throw")
    if (!threw2) println("flatMapLatest did NOT throw")
}

Produces:

Error1 kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 100 ms
flatMapLatest did NOT throw

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsKDoc and API referenceflow

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions