georgiy.shur
01/18/2020, 4:13 PMFlowTestCollectorFlowclass TestCollector<T>(scope: CoroutineScope, flow: Flow<T>) {
    private val collectedValues = mutableListOf<T>()
    private val job = scope.launch { flow.collect { collectedValues.add(it) } }
    fun assertValues(vararg values: T) = run {
        val valuesList = values.toList()
        if (valuesList != collectedValues) {
            fail("\nExpected values: $valuesList\nCollected values:$collectedValues")
        }
        this
    }
    fun dispose() = job.cancel()
}
fun <T> Flow<T>.test(scope: CoroutineScope) = TestCollector(scope, this)@Before
    fun setup() {
        Dispatchers.setMain(Dispatchers.Unconfined)
    }
    @Test
    fun testFlowCollector() = runBlockingTest {
        var firstEmit = true
        val channel = ConflatedBroadcastChannel(0)
        val testCollector = channel.asFlow().onEach {
            if (firstEmit) {
                launch {
                    channel.send(1)
                    channel.send(2)
                }
                firstEmit = false
            }
        }.test(this)
        testCollector.assertValues(0, 1, 2)
        testCollector.dispose()
    }send0, 1, 2java.lang.AssertionError: 
Expected values: [0, 1, 2]
Collected values:[0, 2]1Dico
01/18/2020, 5:55 PMUnconfinedConflatedDico
01/18/2020, 5:59 PMDico
01/18/2020, 6:02 PMhasNext()nextDico
01/18/2020, 6:04 PMreceiveDico
01/18/2020, 6:06 PMgeorgiy.shur
01/19/2020, 11:34 AMBehaviorSubjectchannel.send(State.Loading)
            val data = api.getData() // Retrofit suspended fun
            channel.send(State.Loaded(data))ConflatedBroadcastChannelDico
01/19/2020, 11:40 AMyield()Dico
01/19/2020, 11:44 AMConflatedBroadcastChannelBehaviorSubjectDico
01/19/2020, 11:45 AMgeorgiy.shur
01/19/2020, 11:50 AMDico
01/19/2020, 5:58 PM