在RxJava中对可观察对象进行分组和合并

时间:2019-10-31 05:09:34

标签: rx-java2

我想对RxJava进行以下操作

class Invoice(val dayOfMonth:Int,val amount:Int)

下面是示例月份发票:要处理的清单<发票>

Invoice(3,100)
Invoice(3,150)
Invoice(3,50)
Invoice(4,350)
Invoice(8,400)
Invoice(8,100)

首先,我想像下面这样按月的天分组

Invoice(3,300)
Invoice(4,350)
Invoice(8,500)

然后,我想创建一个包含当月所有日期的列表。假设我们这个月有30天,那么输出列表中必须包含一个空的Invoice对象,该对象在没有发票的那一天插入0金额

所需的输出列表

Invoice(1,0) //Since day 1 is not in the group summed list
Invoice(2,0) //day 2 is also not there
Invoice(3,300)
Invoice(4,350)
Invoice(5,0) 
Invoice(6,0)
Invoice(7,0)
Invoice(8,500)
…..
Invoice(30,0)

希望我已经清楚地说明了这一需求。有人可以回答我一个完全使用RxJava做到的解决方案吗?

2 个答案:

答案 0 :(得分:1)

尝试一下

fun task(invoices: List<Invoice>) =
    Observable.fromIterable(invoices)
        .groupBy { it.dayOfMonth }
        .flatMapSingle { group -> group.reduce(0) { t1, t2 -> t1 + t2.amount }
            .map { group.key to it }}
        .toMap({ it.first }, { it.second })
        .flatMapObservable { map ->
            Observable.range(1, 30)
                .map { Invoice(it, map[it] ?: 0) }
        }

答案 1 :(得分:0)

使用Kotlin标准库中的集合运算符可以轻松实现这一目标,但是在纯RxJava中,您可以使用groupByreduce来实现。

    val invoices = listOf(
        Invoice(3, 100),
        Invoice(3, 150),
        Invoice(3, 50),
        Invoice(4, 350),
        Invoice(8, 400),
        Invoice(8, 100)
    )

    Observable.range(1, 30)
        .map { Invoice(it, 0) } // Create an Observable of Invoice([day], 0)
        .mergeWith(Observable.fromIterable(invoices))
        .groupBy { it.dayOfMonth } // Merge the sources and groupBy day
        .flatMapMaybe { group ->
            group.reduce { t1: Invoice, t2: Invoice ->
                Invoice(t1.dayOfMonth, t1.amount + t2.amount) // Reduce each group into a single Invoice
            }
        }
        .subscribe {
            // Optionally you can call toList before this if you want to aggregate the emissions into a single list
            println(it)
        }