Skip to main content
Donovan LaDuke - Developer

Turbine and the combine operator


Featured in Android Weekly Issue 582

When testing a Flow result from a combine operator using the Turbine library, you will find that the test appears to miss emissions when using awaitItem. If you want to understand more about the cause of the issue, check out this issue on the turbine project and this issue on the kotlinx.coroutines project. While there is no sure-fire solution, a workaround that I found was to add a brief delay in the flows being input to the combine operation during the test. This delay call is skipped when called in the runTest block but ensures the test call doesn't miss emissions. A quick example of a working test is below or see the whole example in this gist.

@Test
fun `this test succeeds`() = runTest {
    val number = (0..2).asFlow().onEach { delay(1) }
    val intro = listOf("Hello").asFlow()

    val combined = combine(intro, number) { one, two ->
        "$one $two"
    }

    combined.test {
        assertEquals("Hello 0", awaitItem())
        assertEquals("Hello 1", awaitItem())
        assertEquals("Hello 2", awaitItem())
        awaitComplete()
    }
}

Now you can get back to writing your tests. Until next time, thanks!

Did you find this content helpful?

Please share this post and be sure to subscribe to the RSS feed to be notified of all future articles!

Want to go above and beyond? Help me out by sending me $1 on Ko-fi. It goes a long way in helping run this site and keeping it advertisement free. Thank you in advance!

Buy me a Coffee on Ko-fi