Hello everyone, is there a way to unit test a shar...
# coroutines
e
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:
Copy code
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
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
Totally missed that, thank you.
151 Views