在 RxJava 中分组和组合 Observable

Grouping and Combining Observables in RxJava

我想用 RxJava 做以下事情

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

下面是要处理的示例monthInvoices:List<发票>

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 天,那么输出列表必须包含在没有发票的日子插入一个金额为 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 的解决方案吗?

使用 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)
        }

试试这个

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) }
        }