简体   繁体   中英

zip with next value with kotlin Flow

how to zip a Flow with the next value as zipWithNext operator for collections?

zipWithNext behaves like:

val letters = ('a'..'f').toList()
val pairs = letters.zipWithNext()

println(letters) // [a, b, c, d, e, f]
println(pairs) // [(a, b), (b, c), (c, d), (d, e), (e, f)]

but in my case letters would be:

val letters = flowOf('a'..'f')

bonus points:

i tried flowOf(1, 2, 3).scan(emptyList<Int>()) { acc, value -> acc + value }.toList() on https://play.kotlinlang.org/ but doesn't find flowOf what import or else i'm missing there?

One possible solution is:

val letters = ('a'..'f').toList().toTypedArray()
val lettersFlow = flowOf(*letters)
val result = lettersFlow.scan(Pair<Char, Char>('a','a')) { acc, value -> Pair(acc.second, value) }.drop(2).toList()
println(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM