将分组的可观测值的排放收集到一个列表中 [英] Collect grouped observables' emissions into one list

查看:34
本文介绍了将分组的可观测值的排放收集到一个列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下用例(这当然是一个人为的例子,但是一旦我知道答案,我将能够将其移植到我要解决的实际问题中):

I have the following use case (this is of course a contrived example, but once I know the answer, I will be able to port it to a real problem I am to solve):

  1. 获取整数列表.
  2. 按 % 4 操作的结果对它们进行分组
  3. 将每个组的元素收集到列表中
  4. 忽略元素少于 3 个元素的任何组/列表
  5. 发出单个列表,其元素是在步骤 #3 中创建的列表

这是我当前的代码:

    Observable
            .from(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12))
            .groupBy(item -> item % 4)
            .subscribe(groupedObservable -> {
                groupedObservable
                        .toList()
                        .filter(list -> list.size() > 2)
                        .subscribe(result -> {
                            System.out.printf("%d results %s%n", result.size(), result);
                        });
            });

它的输出是:

4 results [0, 4, 8, 12]
3 results [2, 6, 10]
3 results [3, 7, 11]

所以它打印出每个组有多少个元素,然后是元素列表.我希望输出是(我实际上并不关心键):

So it prints out how many elements each group has and then the list of elements. I would like the output to be (I actually don't care about the keys):

3 个结果:[[0, 4, 8, 12], [2, 6, 10], [3, 7, 11]]

3 results: [[0, 4, 8, 12], [2, 6, 10], [3, 7, 11]]

即以某种方式将分组的 observable 压平到一个列表中.我没有这样做.例如,在 filter 之后添加 .flatMap(integers -> Observable.just(integers)) 不会改变任何东西,因为它只会影响每个分组的 observable,而不是整个流.有没有办法满足我的要求?

i.e. somehow flatten the grouped observables into one list. I fail to do so. For example, adding .flatMap(integers -> Observable.just(integers)) after the filter doesn't change anything, as it just influences each grouped observable, not the whole stream. Is there a way to fulfill my requirements?

推荐答案

我不确定我是否理解正确,但根据所需的输出,这里是您可能正在寻找的代码:

I'm not sure if I've understood you correctly, but based on the desired output here is the code you might be looking for:

public static void main(final String[] args) throws Exception {
    Observable.from(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12))
            .groupBy(item -> item % 4)
            .flatMap(Observable::toList)
            .filter(integers -> integers.size() > 2)
            .toList()
            .subscribe(result -> {
                System.out.printf("%d results %s%n", result.size(), result);
            });
}

这篇关于将分组的可观测值的排放收集到一个列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆