pairwise

fun <T> Flow<T>.pairwise(): Flow<Pair<T, T>>(source)

Groups pairs of consecutive emissions together and emits them as a pair.

Emits the (n)th and (n-1)th events as a pair. The first value won't be emitted until the second one arrives. The resulting Flow is empty if this Flow emits less than two elements.

This operator is more optimizer than bufferCount version:

val flow: Flow<T>

val result: Flow<Pair<T, T>> = flow
.bufferCount(bufferSize = 2, startBufferEvery = 1)
.mapNotNull {
if (it.size < 2) null
else it[0] to it[1]
}

fun <T, R> Flow<T>.pairwise(transform: suspend (a: T, b: T) -> R): Flow<R>(source)

Groups pairs of consecutive emissions together and emits the result of applying transform function to each pair.

The first value won't be emitted until the second one arrives. The resulting Flow is empty if this Flow emits less than two elements.

This operator is more optimizer than bufferCount version:

val flow: Flow<T>

val result: Flow<R> = flow
.bufferCount(bufferSize = 2, startBufferEvery = 1)
.mapNotNull {
if (it.size < 2) null
else transform(it[0], it[1])
}

Parameters

transform

A function to apply to each pair of consecutive emissions.