Is there a flow operator that provides previous em...
# flow
m
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.
Also
scan
is not an option as I do not want every historical emission but just last 2 ones.
b
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
Yes I already wrote something similar as this
zipWithNext
. Was just wondering if there is something provided by flow already.
e
It would be great if you explain your
zipWithNext
use-case in more details in https://github.com/kotlin/kotlinx.coroutines/issues