https://kotlinlang.org logo
Title
e

Eury Perez

04/24/2023, 12:54 PM
Hello everyone, is there a way to unit test a shared flow that emits before collecting, for instance: I'm emitting in the viewModel's init block. Here's what I'm trying:
val values = mutableListOf<Int>()
val sharedFlow = MutableSharedFlow<Int>()
sharedFlow.emit(0)
val job = launch { // <------
    stateFlow.collect {
        values.add(it)
    }
}
runCurrent()
sharedFlow.emit(1)
runCurrent()
sharedFlow.emit(2)
runCurrent()
sharedFlow.emit(3)
runCurrent()
job.cancel()

assertEquals(listOf(0, 1, 2, 3), values)
A similar test passes with stateflow
t

Thiago Souto

04/24/2023, 1:03 PM
You can use
Turbine
from CashApp https://github.com/cashapp/turbine
z

zsmb

04/24/2023, 1:38 PM
With a
SharedFlow
if there’s no cache configured you have to have the collector ready in time to collect it, otherwise you’ll just miss it. Also, slightly unrelated: you can launch the collecting coroutine in backgroundScope to avoid having to keep a reference to its job and cancelling it manually at the end of the test.