https://kotlinlang.org logo
Title
r

reactormonk

07/07/2022, 5:43 PM
Is there a
mapWithState
or similar for Channels, where I can keep a consistent state around?
j

Joffrey

07/07/2022, 5:52 PM
Could you please describe what you mean with an example?
r

reactormonk

07/07/2022, 5:55 PM
val tagFound = onChange.mapWithState(StateAbsent) { oldState, newState -> if (oldState == newState) { SomethingChanged } else { NothingChanged }
}
j

Joffrey

07/07/2022, 6:01 PM
First, I would say if you want fancy operations on channels, you usually have to convert them to flows. Then, I'm not sure I entirely understand what types you would be dealing with here, but maybe
runningFold
could help you?
r

reactormonk

07/07/2022, 6:02 PM
Looks correct, thanks!
I've been using channel and flow somewhat interchangably, gotta read up on the difference
j

Joffrey

07/07/2022, 6:05 PM
Channels are more meant as a synchronization and communication primitive, more low level. OTOH, flows have a lot of useful operators to deal with your business logic, so they are more convenient to use. One crucial difference though, is that flows are cold and channels are hot. Hot means that the producer of values exists and works (somewhat) independently of whether there are consumers. Cold flows, on the other hand, need a collector to start doing their work. That said, there are a bunch of subtleties around this: there are now hot flows since the addition of
StateFlow
and
ShareFlow