I'm having a curious issue when dealing with flatMapLatest
and emptyFlow
as well as firstOrNull
.
Scenario A:
val dataFlow: Flow<Boolean> = emptyFlow()
launch {
val data = dataFlow.firstOrNull() // returns data = null
}
Scenario B:
val rootFlow: MutableStateFlow<Boolean?> = MutableStateFlow(null)
val dataFlow: Flow<Boolean> = rootFlow.flatMapLatest {
emptyFlow()
}
launch {
val data = dataFlow.firstOrNull() // blocks and does not return any value
}
So my question would be, why does firstOrNull
not return any value in Scenario B.
I'm seeing that flatMapLatest is being called with the initial null
value of the mutable state flow.
rootFlow
is a StateFlow
which means it never ends.
Your dataFlow
is a transformation of rootFlow
so it will not end until source flow ends.
That means in this case dataFlow.firstOrNull()
will suspend forever as it keeps transforming each value of rootFlow
into empty flows.