Home > Mobile >  Complete kotlin flow successfully and emit partially data on some condition
Complete kotlin flow successfully and emit partially data on some condition

Time:09-15

I'm struggling to get completed flow with some result without any exception on some condition. Let's say I'm receiving flow of lists. I want to emit some of its data and then complete without any exception, for example:

class FlowTest {

    @Test
    internal fun `should emit partially when some condition fulfilled`() = runTest {
        val testFlow = flowOf(listOf(1,2), listOf(3,4), listOf(5,6))
            .transform {
                if(it.contains(4)) {
                    emit(it[0])
                    cancel()
                } else {
                    emit(it[0])
                    emit(it[1])
                }
            }

        assertEquals(3, testFlow.toList().size, "Should contain [1,2,3]")
    }
}

It fails because of JobCancellationException. I could also make some filter and emit specific things, but then listOf(5,6) would also go through filters and this is bad since I'd like to close flow as early as some condition is fulfilled.

CodePudding user response:

Use transformWhile. This lets you return a true or false value indicating whether to continue the flow.

.transformWhile {
    if(it.contains(4)) {
        emit(it[0])
        false // stop the flow
    } else {
        emit(it[0])
        emit(it[1])
        true // continue the flow
    }
}
  • Related