如何链接多个RxJava的groupBy()方法,例如groupBy().groupBy()

cha*_*eng 10 java android reactive-programming rx-java

给定输入:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Run Code Online (Sandbox Code Playgroud)

将数字分组为奇数或偶数,然后小于或大于5.

预期产量:

[[1, 3, 5], [2, 4], [6, 8, 10], [7, 9]]
Run Code Online (Sandbox Code Playgroud)

输出的顺序不受限制.

我现在使用以下方法:

Observable.range(1, 10)
    .groupBy(n -> n % 2 == 0)
    .flatMap((GroupedObservable<Boolean, Integer> g) -> {
        return Observable.just(g).flatMap(ObservableUtils.<Boolean, Integer>flatGroup()).groupBy(n -> n > 5);
    })
    .subscribe((final GroupedObservable<Boolean, Integer> g) -> {
        Observable.just(g).flatMap(ObservableUtils.<Boolean, Integer>flatGroup()).forEach(n -> println(g + ": " + n));
    });
Run Code Online (Sandbox Code Playgroud)

请注意,ObservableUtils是我编写的,用于简化代码.

但我对它并不满意,因为它还不够简单,只能表明目标.

我的期望如下:

Observable.range(1, 10)
    .groupBy(n -> n % 2 == 0)
    .groupBy(n -> n > 5)
    .subscribe(...);
Run Code Online (Sandbox Code Playgroud)

现在我只能把它缩小为:

Observable.range(1, 10)
    .lift(new OperatorGroupByGroup(n -> n % 2 == 0))
    .lift(new OperatorGroupByGroup(n -> n > 5))
    .subscribe(...);
Run Code Online (Sandbox Code Playgroud)

我仍然需要编写稍微复杂的OperatorGroupByGroup类.有什么改进的建议吗?

And*_*hen 2

我为 OperatorGroupByGroup 编写了一个基于 OperatorGroupBy 的示例:

https://github.com/yongjhih/RxJava-GroupByTest

用法:

git clone https://github.com/yongjhih/RxJava-GroupByTest.git
./gradlew execute
Run Code Online (Sandbox Code Playgroud)

但由于我的 OperatorGroupByGroup 实现,我修改了测试代码:

    Observable.range(1, 10)
    .lift(new OperatorGroupByGroup<Integer, Boolean, Integer>(n -> n % 2 == 0))
    .lift(new OperatorGroupByGroup<GroupedObservable<Boolean, Integer>, Boolean, Integer>(n -> n > 5))
    .subscribe((final GroupedObservable<Boolean, Integer> g) -> {
        Observable.just(g).flatMap(ObservableUtils.<Boolean, Integer>flatGroup()).forEach(n -> println(g + ": " + n));
    });
Run Code Online (Sandbox Code Playgroud)

我想有人会做得更好。