Is there a `mapWithState` or similar for Channels,...
# coroutines
r
Is there a
mapWithState
or similar for Channels, where I can keep a consistent state around?
j
Could you please describe what you mean with an example?
r
Copy code
val tagFound = onChange.mapWithState(StateAbsent) { oldState, newState -> if (oldState == newState) { SomethingChanged } else { NothingChanged }
}
j
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
Looks correct, thanks!
I've been using channel and flow somewhat interchangably, gotta read up on the difference
j
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