[英]Multiple Observable execution with RxJava
我定義了兩個Observable,我將它們稱為:
Observable<Boolean> statusObser1 = reactiveApiConsumer.syncGradesSet1(subListDtos.get(0));
Observable<Boolean> statusObser2 = reactiveApiConsumer.syncGradesSet2(subListDtos.get(1));
statusObser1.toBlocking().first();
statusObser2.toBlocking().first();
但是問題在於, statusObser2
僅在statusObser1
完成之后statusObser1
執行。 相反,我希望兩個觀察者並行執行,即statusObser2
不應該等待statusObser1
完成。
由於您正在阻塞( toBlocking()
)並等待其響應,因此它們會順序執行。
而是訂閱它們。 分別:
Observable<Boolean> statusObser1 = ...
Observable<Boolean> statusObser2 = ...
statusObser1.subscribe(System.out::println); //Example
statusObser2.subscribe(System.out::println); //Example
或使用Zip運算符:
public static int doSomethingWithBothValues(Boolean a, Boolean b) {
...
}
...
Observable<Boolean> statusObser1 = ...
Observable<Boolean> statusObser2 = ...
Observable.zip(statusObser1,statusObser2, this::doSomethingWithBothValues);
在此處查看有關Zip運算符的更多詳細信息。
在這兩種情況下,如果可觀察對象是異步的,則它們將並行執行。
您可以使用其他運算符來合並兩個運算符的結果,而不會阻塞它們中的任何一個。
嘗試多線程。
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
方法將在新的Thread中執行該執行,並且兩個執行都將在單獨的Thread中執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.