消耗观察者同时发出的值

时间:2015-01-23 11:47:34

标签: java java-8 reactive-programming rx-java

我正在使用RxJava学习反应式编程,并希望在单个执行线程中同时使用emmited值而不会阻塞。

        Observable
            .interval(50, TimeUnit.MILLISECONDS)
            .take(5)
            .subscribe(new Action1<Long>() {
                @Override
                public void call(Long counter) {
                    sleep(1000);
                    System.out.println("Got: " + counter + " thread : "+ Thread.currentThread().getName());
                }
            });

    sleep(10000);

我会得到这个输出

Got: 0 thread : RxComputationThreadPool-1
Got: 1 thread : RxComputationThreadPool-1
Got: 2 thread : RxComputationThreadPool-1
Got: 3 thread : RxComputationThreadPool-1
Got: 4 thread : RxComputationThreadPool-1

我如何处理异步中的每个事件?像这样

Got: 0 thread : RxComputationThreadPool-1
Got: 1 thread : RxComputationThreadPool-2
Got: 2 thread : RxComputationThreadPool-3
Got: 3 thread : RxComputationThreadPool-4
Got: 4 thread : RxComputationThreadPool-5

1 个答案:

答案 0 :(得分:4)

在Rx中,observable表示并发 1 ,因此要相互处理通知,必须将每个通知投影到一个observable中。

flatMap是异步顺序组合运算符。它将来自可观察源的每个通知投影到一个observable中,从而允许您同时处理每个输入值。然后,它将每个计算的结果合并为具有非重叠通知的展平可观察序列。

附录:

selector flatMap中,根据目标平台,通常有多种方法可以创建并发observable。我不了解Java,但在.NET中,您通常会使用Observable.Start来引入并发或使用异步方法(async/await)来利用本机异步,这通常是可取的。< / p>

1 从技术上讲, cold observable的单个订阅(观察者)可以在Rx中启用并发性,尽管通常可以方便地考虑可观察量而不是。有关详细信息,请参阅this answer