Why does `stateIn` need an initial value? I keep w...
# flow
m
Why does
stateIn
need an initial value? I keep writing
.stateIn(…, …, initialValue = null).filterNotNull()
e
what would
StateFlow.value
return without an initial value?
m
Good point. I don’t care about that property but it’s there. I’ve always wondered why it isn’t a
suspend fun value()
instead.
e
g
Because state flow was designed for use cases, where default value is useful, such as UI state Also suspend value() is the same as existing suspend first()
m
So it was designed for a subset of potential use cases 😉 Anyway, I don’t think it will be changed anymore. So I have to work around it or make my own operator.
e
perhaps SharedFlow/.shareIn() would be a better fit for you
m
I think I’d then have to add
.conflate().distinctUntilChanged()
before each
.shareIn
to achieve the same behavior.
So at the end both approaches are quite repetitive.
g
But MutableSharedFlow doing the same waht you need, isn’t it?
it doesn’t have any default value, you can control how buffere works on overfloiw
So it was designed for a subset of potential use cases
Exactly. as any other abstraction I believe, has some use cases in mind
Looks that this what you need
MutableSharedFlow(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
But yeah, you still need distinctUntilChanged if you want behaviour of StateFlow
anyway, I don’t think you need something custom, just a combination of a couple existing operators