简体   繁体   English

RxJava的多个可观察执行

[英]Multiple Observable execution with RxJava

I have two Observables define and I am calling them as below: 我定义了两个Observable,我将它们称为:

Observable<Boolean> statusObser1 = reactiveApiConsumer.syncGradesSet1(subListDtos.get(0));
Observable<Boolean> statusObser2 = reactiveApiConsumer.syncGradesSet2(subListDtos.get(1));
statusObser1.toBlocking().first();
statusObser2.toBlocking().first();

But the problem is that statusObser2 executes only after statusObser1 has completed. 但是问题在于, statusObser2仅在statusObser1完成之后statusObser1执行。 Instead I want both observers to execute in parallel, ie statusObser2 shouldn't wait for statusObser1 to complete. 相反,我希望两个观察者并行执行,即statusObser2不应该等待statusObser1完成。

They execute sequentially since you're blocking ( toBlocking() ) and waiting for their response. 由于您正在阻塞( toBlocking() )并等待其响应,因此它们会顺序执行。

Instead, subscribe to them. 而是订阅它们。 Either individually: 分别:

Observable<Boolean> statusObser1 = ...
Observable<Boolean> statusObser2 = ...
statusObser1.subscribe(System.out::println); //Example
statusObser2.subscribe(System.out::println); //Example

Or using the Zip operator: 或使用Zip运算符:

public static int doSomethingWithBothValues(Boolean a, Boolean b) {
    ...
}

...

Observable<Boolean> statusObser1 = ...
Observable<Boolean> statusObser2 = ...
Observable.zip(statusObser1,statusObser2, this::doSomethingWithBothValues);

see more details about the Zip operator here . 在此处查看有关Zip运算符的更多详细信息。

In both cases, if the observables are asynchronous, they will be executed in parallel. 在这两种情况下,如果可观察对象是异步的,则它们将并行执行。

There are other operators you can use to combine the results of both your operators without blocking either of them. 您可以使用其他运算符来合并两个运算符的结果,而不会阻塞它们中的任何一个。

Try MultiThreading. 尝试多线程。

Observable<Boolean> statusObser1 = reactiveApiConsumer.syncGradesSet1(subListDtos.get(0));
Observable<Boolean> statusObser2 = reactiveApiConsumer.syncGradesSet2(subListDtos.get(1));
startThread(statusObser1);
startThread(statusObser2);

public void startThread(Observable<Boolean> statusObser) {
    new Thread() {
        @Override
        public void run() {
            statusObser.toBlocking().first();
        }
    }.start();
}

startThread method will execute the execution in a new Thread, and both executions wil executed in seperate Thread. startThread方法将在新的Thread中执行该执行,并且两个执行都将在单独的Thread中执行。

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

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