Kotlin Flow的GroupBy运算符

问题描述 投票:1回答:2

我正在尝试从RxJava切换到Kotlin Flow。流量确实令人印象深刻。但是,现在在kotlin Flow中是否有类似于RxJava的“ GroupBy”的运算符?

kotlin kotlin-coroutines flow
2个回答
1
投票

这是groupBy的简单实现,发出(key, list(t))对:

fun <T, K> Flow<T>.groupBy(keyFn: (T) -> K): Flow<Pair<K, List<T>>> = flow {
    val storage = mutableMapOf<K, MutableList<T>>()
    collect { t -> storage.getOrPut(keyFn(t)) { mutableListOf() } += t }
    storage.forEach { (k, ts) -> emit(k to ts) }
}

对于此示例:

suspend fun main() {
    val input = 1..10
    input.asFlow()
            .groupBy { it % 2 }
            .collect { println(it) }
}

打印

(1, [1, 3, 5, 7, 9])
(0, [2, 4, 6, 8, 10])

0
投票

尚未,但您可以查看此库https://github.com/akarnokd/kotlin-flow-extensions

© www.soinside.com 2019 - 2024. All rights reserved.