简体   繁体   English

RxJava groupBy和后续的阻塞操作(onComplete缺失?)

[英]RxJava groupBy and subsequent blocking operations (onComplete missing?)

I have boiled my problem down into the following snippet: 我已将问题归结为以下代码段:

Observable<Integer> numbers = Observable.just(1, 2, 3);

Observable<GroupedObservable<Integer,Integer>> outer = numbers.groupBy(i->i%3);
System.out.println(outer.count().toBlocking().single());

which blocks interminably. 无休止地阻止。 I've been reading several posts and believe I understand the problem: GroupedObservables will not call onComplete until their inner Observables have also been completed. 我一直在阅读 几篇 文章,并且相信我理解了这个问题:GroupedObservables在内部Observables也已完成之前不会调用onComplete。 Unfortunately though I still can't get the above snippet to print! 不幸的是,虽然我仍然无法得到上面的代码片段来打印!

For example, the following: 例如,以下内容:

Observable<Integer> just = Observable.just(1, 2, 3);

Observable<GroupedObservable<Integer,Integer>> groupBy = just.groupBy(i->i%3);
groupBy.subscribe(inner -> inner.ignoreElements());
System.out.println(groupBy.count().toBlocking().single());

still does nothing. 仍然什么也没做。 Have I misunderstood the problem? 我误解了这个问题吗? Is there another problem? 还有其他问题吗? In short, how can I get the above snippets to work? 简而言之,我如何才能使上述代码片段起作用?

Many thanks in advance, Dan. 非常感谢,Dan。

Yes, you have to consume the groups in some fashion. 是的,你必须以某种方式消费这些群体。 Your second example doesn't work because you have two independent subscription to the grouping operation. 您的第二个示例不起作用,因为您有两个独立的分组操作订阅。

Usually, the solution is flatMap , but not not with ignoreElements because that will just complete and count won't get any elements. 通常,解决方案是flatMap ,但不是ignoreElements因为它只会完成并且count将不会获得任何元素。 Instead, you can use takeLast(1) : 相反,您可以使用takeLast(1)

Observable.just(1, 2, 3)
    .groupBy(k -> k % 3)
    .flatMap(g -> g.takeLast(1))
    .count()
    .toBlocking()
    .forEach(System.out::println);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM