Marek Kubiczek
11/11/2020, 8:26 AMrunningReduce
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.scan
is not an option as I do not want every historical emission but just last 2 ones.bezrukov
11/11/2020, 10:34 AMrunningReduce
for your case:
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:
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
}
}
Marek Kubiczek
11/11/2020, 10:49 AMzipWithNext
. Was just wondering if there is something provided by flow already.elizarov
11/11/2020, 11:54 AMzipWithNext
use-case in more details in https://github.com/kotlin/kotlinx.coroutines/issues