Simon Lin
03/23/2021, 1:57 AMephemient
03/23/2021, 3:44 AMfun <T> Flow<T>.zipWithNext(initValue: T): Flow<Pair<T, T>> = flow {
var lastValue = initValue
collect {
emit(lastValue to it)
lastValue = it
}
}
flowOf(1, 2, 3, 4, 5, 6).zipWithNext(0).toList() ==
listOf(0 to 1, 1 to 2, 2 to 3, 3 to 4, 4 to 5, 5 to 6)
fun <T> Flow<T>.windowed(
size: Int,
step: Int = 1,
partialWindows: Boolean = false
): Flow<List<T>> {
require(size > 0 && step > 0)
return flow {
val window = ArrayDeque<T>(size)
var count = 0
collect {
if (window.size >= size) window.removeFirst()
window.add(it)
if (window.size == size && count == 0) emit(window.toList())
count = (count + 1) % step
}
if (partialWindows) {
while (window.size > 1) {
window.removeFirst()
if (count == 0) emit(window.toList())
count = (count + 1) % step
}
}
}
}
flowOf(1, 2, 3, 4, 5, 6).onStart { emit(0) }.windowed(2).toList() ==
listOf(listOf(0, 1), listOf(1, 2), listOf(2, 3), listOf(3, 4), listOf(4, 5), listOf(5, 6))
Natsuki(开元米粉实力代购)
03/23/2021, 11:27 AMfold
listOf(1, 2, 3).asFlow().fold(0) { prev, ele ->
println(prev to ele)
ele
}
ephemient
03/23/2021, 7:04 PMList<>
then you already have .zipWithNext()
and .windowed()
in stdlib 🙂Simon Lin
03/25/2021, 2:03 AM