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
s

stojan

04/24/2023, 1:02 PM
in that scenario the value is ignored: https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-mutable-shared-flow/emit.html
If there are no subscribers, the buffer is not used. Instead, the most recently emitted value is simply stored into the replay cache if one was configured, displacing the older elements there, or dropped if no replay cache was configured.
emphasis mine
e

Eury Perez

04/24/2023, 1:18 PM
Totally missed that, thank you.