为 Kotlin Flow 实现 groupBy 扩展

Implementing a groupBy extension for Kotlin Flow

我的流程是这样的:Flow<List<Transaction>>

每个Transaction对象都有一个Category对象

我想要的是一个扩展功能,可以根据 Category

对交易进行分组

这是我试过的:

inline fun <T, K> Flow<Iterable<T>>.groupIterableBy(crossinline keySelector: (T) -> K): Flow<Map<K, MutableList<T>>> = map {
        val storage = HashMap<K, MutableList<T>>()
        it.map{ element ->
            val key = keySelector(element)
            if (storage[key] == null){
                storage[key] = mutableListOf()
            }
            storage[key]!!.add(element)
        }
        return@map storage
}

这很好用,但我不觉得它是以干净的方式编程的。 有没有人建议让这个功能更简洁?

根据 IR42 的评论,这应该可行。为什么不使用

Iterable.groupBy()

划痕示例:

data class Tra(
    val cat: Cat
)

data class Cat(
    val name: String
)

val flow = flowOf(
    listOf(
        Tra(Cat("A")),
        Tra(Cat("B")),
        Tra(Cat("D")),
        Tra(Cat("B"))
    ),
    listOf(
        Tra(Cat("A")),
        Tra(Cat("C")),
        Tra(Cat("B")),
        Tra(Cat("A")),
        Tra(Cat("C"))
    )
)

inline fun <T, K> Flow<Iterable<T>>.groupIterableBy(crossinline  keySelector: (T) -> K): Flow<Map<K, List<T>>> =
    map { it.groupBy(keySelector) }

val groupedFlow = flow.groupIterableBy{it.cat.name}

runBlocking {
    groupedFlow
        .collect {
            println(it)
        }
}

它打印:

{A=[Tra(cat=Cat(name=A))], B=[Tra(cat=Cat(name=B)), Tra(cat=Cat(name=B))], D=[Tra(cat=Cat(name=D))]}
{A=[Tra(cat=Cat(name=A)), Tra(cat=Cat(name=A))], C=[Tra(cat=Cat(name=C)), Tra(cat=Cat(name=C))], B=[Tra(cat=Cat(name=B))]}

这是您要找的结果吗?