Hi, I have a question on StateFlow: is it possible...
# flow
g
Hi, I have a question on StateFlow: is it possible to fold a flow into a stateflow? I.e. is there a function like
Copy code
fun <T, R> Flow<T>.foldToStateFlow(initial: R, op: (acc: R, next: T) -> R): StateFlow<R>
s
Doing the fold and turning it into a state flow are really two different things. The type of fold you're looking for is called
runningFold
(alias
scan
), but it returns an ordinary flow, not a state flow. To get a state flow, you would still need to provide a coroutine scope and use an operator like
stateIn
to actually collect the upstream values. It's kind of a pain that
runningFold
and
stateIn
both want the
initial
value, though... I'm not sure what's the cleanest solution to that little conundrum.
👍 1
g
Great,
runningFold
was the missing link. That works for me! Thnx!