Hi all! I would like to know if a StateFlow value ...
# coroutines
d
Hi all! I would like to know if a StateFlow value has changed (
myStateFlow.value = value
) currently I have
Copy code
myStateFlow
        .withIndex()
        .onEach { if (it.index > 0) doSomething() }
        .map { it.value }
but I dont find it very pretty… do you see better ways to do it? tks!
z
drop(1)
since you know the first emission will always be the cached one.
d
indeed in my use case I dont need to collect the first value; thanks. But I am curious though how would you do it if you want to collect the first/initial value?
z
You don't need anything special then, just collect the flow.
StateFlow
already acts as though
distinctUntilChanged
has been applied, so it will only emit distinct values.
d
yes but I would still like to know if the value has changed (flow emitted a second value like in my snippet)
z
I don't think I fully understand what you mean. The flow tells you when the value changes by emitting it. The fact that the emission occurred tells you the value has changed. Could you share more about your actual use case or maybe some code about what you actually want to do when this happens?
d
But the initial value is also emitted no (
MutableStateFlow(0).collect()
would emit
0
no) ?
g
Yes, it would emit 0, but you can do "drop(1)"
d
yes but what if I would like to collect this 0 and know if there is a “change” (= a new value emitted/collected) (sorry for not being very clear)
wouldnt
drop(1)
filter out
0
collection?
anyway; I should try before asking; sorry
z
Yes. Your index solution would work. If you want it to be more explicit, you could make your own operator that sends you a boolean to indicate whether it’s the first emission or not, although I think that’s probably overkill for a single use case like this, the index thing is fine.
👌 1
g
Ah, got you case. Wouldnt be better use onStart operator instead?
But only if you don't need to know initial value
d
hmm, not sure to see how you would use
onStart
here?
g
onStart will be called when someone start consuming flow