Skip to content

How can I test back-pressure? #157

@caiofaustino

Description

@caiofaustino

Hi, I was wondering if there is any mechanism to test the same back-pressure behavior that collect() has.
Here is an example on the different behaviors I encounter.

@Test
public fun `when I test - flow should backpressure`(): TestResult = runTest {
    val myFlow:Flow<Int> = flow {
        println("emitting 1")
        emit(1)
        println("emitted 1")
        delay(10)
        println("emitting 2")
        emit(2)
        println("emitted 2")
        delay(10)
        println("emitting 3")
        emit(3)
        println("emitted 3")
    }


    println("COLLECT")
    myFlow.collect {
        println("collected $it")
        delay(50)
    }

    println()
    println("TEST")
    // Test
    myFlow.test {
        val item1 = awaitItem()
        println("collected $item1")
        delay(50)
        val item2 = awaitItem()
        println("collected $item2")
        delay(50)
        val item3 = awaitItem()
        println("collected $item3")
        awaitComplete()
    }
}

Prints

COLLECT
emitting 1
collected 1
emitted 1
emitting 2
collected 2
emitted 2
emitting 3
collected 3
emitted 3

TEST
emitting 1
emitted 1
emitting 2
emitted 2
emitting 3
emitted 3
collected 1
collected 2
collected 3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions