Hi, maybe this is a trivial, but I’m trying to cre...
# flow
g
Hi, maybe this is a trivial, but I’m trying to create a new Flow from a StateFlow that is based on the current and the previous state. Eg. a StateFlow<Int> with state 2 and then 5 and then 1 would cause the flow to emit 3 and then -4.
I’m currently working in the lines of:
Copy code
val sf: StateFlow<Int> = MutableStateFlow(0)
var state: Int = sf.value
val someFlow = sf.map {
    val diff = it - state
    state = it
    diff
}
But I feel that there could be some better solution.
g
Wow, I did not consider using a fold, thanks!
Lovely:
Copy code
val stateFlow: StateFlow<Int> = MutableStateFlow(0)
stateFlow
    .runningFold(0 to 0) { (_, last), next -> last to next }
    .map { (last, current) -> last - current }
🧘 1