https://kotlinlang.org logo
#flow
Title
# flow
c

Chris Fillmore

11/25/2021, 2:35 PM
Is there an existing Flow method like this? I don’t see one, just curious if I’m missing it.
Copy code
fun <T> Flow<T>.onChange(action: (oldValue: T, newValue: T) -> Unit): Flow<T>
Similar to
Delegates.observable
w

wasyl

11/25/2021, 2:38 PM
Perhaps you can achieve what you want with
runningFold
or
runningReduce
?
c

Chris Fillmore

11/25/2021, 2:38 PM
Ooh good idea
Thanks for the tip, I’ll try it out
e

ephemient

11/25/2021, 5:16 PM
I could also imagine either one of these, similar to Iterable extensions,
Copy code
fun <T> Flow<T>.zipWithNext(): Flow<Pair<T, T>>
fun <T, R> Flow<T>.zipWithNext(action: suspend FlowCollector<R>.(oldValue: T, newValue: T) -> Unit): Flow<R>
or a modification of
distinctUntilChangedBy
,
Copy code
fun <T> Flow<T>.distinctUntilChangedWith(predicate: (T, T) -> Boolean): Flow<T>
to be proposed as additions to Flow
c

Chris Fillmore

11/25/2021, 5:29 PM
Fwiw this is what I implemented
Copy code
fun <T> Flow<T>.onChange(action: suspend (oldValue: T, newValue: T) -> Unit): Flow<T> {
    return runningReduce { old, new ->
        action(old, new)
        new
    }
}
I named it
onChange
just because in my particular case I’m dealing with state changes in a
StateFlow
, but another name might be more suitable to a general purpose
Flow
2 Views