Is there a flow operator that provides previous emission? I would like to emit something based on current and previous emission. Tried
runningReduce
but it’s not 100% what I need as I always want two last values from upstream rather then the current Value and accumalated value.
Marek Kubiczek
11/11/2020, 8:32 AM
Also
scan
is not an option as I do not want every historical emission but just last 2 ones.
b
bezrukov
11/11/2020, 10:34 AM
you can adapt
runningReduce
for your case:
Copy code
flow.runningReduce { (prev, _), next ->
// do what you want with prev,next
val mappedResult = mapper(prev, next)
next to mappedResult
}.map { it.second }
But if you use this pattern widely, you can write this function, it's pretty easy:
Copy code
public fun <T> Flow<T>.zipWithNext(operation: suspend (value: T, next: T) -> R): Flow<R> = flow {
val NULL = Any()
var prev: Any? = NULL
collect { value ->
if (prev !== NULL) {
emit(operation(prev as T, value))
}
prev = value
}
}
m
Marek Kubiczek
11/11/2020, 10:49 AM
Yes I already wrote something similar as this
zipWithNext
. Was just wondering if there is something provided by flow already.