I’m writing some documentation for my team around ...
# flow
p
I’m writing some documentation for my team around testing with Flows and I’ve found a simple example that I don’t understand. Given a class that exposes both a suspending and non-suspending way to add a value to a SharedFlow:
Copy code
class MyFlowRepository(private val applicationScope: CoroutineScope) {
    private val mutableSharedFlow = MutableSharedFlow<Data>()

    val dataFlow = mutableSharedFlow
        .shareIn(applicationScope, SharingStarted.Eagerly, replay = 1)

    suspend fun addDataSuspending(data: Data) {
        mutableSharedFlow.emit(data)
    }

    fun addData(data: Data) {
        applicationScope.launch {
            mutableSharedFlow.emit(data)
        }
    }
}
This test fails:
Copy code
class MyFlowRepositoryTest {
    private val testScope = TestScope()

    @Test
    fun test() = testScope.runTest(dispatchTimeoutMs = 2_000) {
        val repository = MyFlowRepository(testScope.backgroundScope)
        repository.dataFlow.test {
            repository.addDataSuspending(Data("11"))
            assertEquals(expected = Data("11"), awaitItem())

            repository.addData(Data("10"))
            assertEquals(expected = Data("10"), awaitItem())
        }
    }
}
but if I reverse the order of the two calls in the test code, it passes:
Copy code
@Test
    fun test() = testScope.runTest(dispatchTimeoutMs = 2_000) {
        val repository = MyFlowRepository(testScope.backgroundScope)
        repository.dataFlow.test {
            repository.addData(Data("10"))
            assertEquals(expected = Data("10"), awaitItem())

            repository.addDataSuspending(Data("11"))
            assertEquals(expected = Data("11"), awaitItem())
        }
    }
Why does the order affect the test outcome here?