https://kotlinlang.org logo
Title
d

dany

06/25/2020, 12:56 PM
Hi all! I would like to know if a StateFlow value has changed (
myStateFlow.value = value
) currently I have
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

Zach Klippenstein (he/him) [MOD]

06/25/2020, 1:12 PM
drop(1)
since you know the first emission will always be the cached one.
d

dany

06/25/2020, 1:19 PM
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

Zach Klippenstein (he/him) [MOD]

06/25/2020, 1:22 PM
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

dany

06/25/2020, 1:34 PM
yes but I would still like to know if the value has changed (flow emitted a second value like in my snippet)
z

Zach Klippenstein (he/him) [MOD]

06/25/2020, 1:49 PM
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

dany

06/25/2020, 2:41 PM
But the initial value is also emitted no (
MutableStateFlow(0).collect()
would emit
0
no) ?
g

gildor

06/25/2020, 3:04 PM
Yes, it would emit 0, but you can do "drop(1)"
d

dany

06/25/2020, 3:07 PM
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

Zach Klippenstein (he/him) [MOD]

06/25/2020, 3:09 PM
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

gildor

06/25/2020, 3:13 PM
Ah, got you case. Wouldnt be better use onStart operator instead?
But only if you don't need to know initial value
d

dany

06/25/2020, 3:21 PM
hmm, not sure to see how you would use
onStart
here?
g

gildor

06/25/2020, 3:31 PM
onStart will be called when someone start consuming flow