簡體   English   中英

使用RxJava異步調用多個同步任務

[英]Call multiple synchronous tasks asynchronously using RxJava

我有一個由Futures表示的異步任務,該任務在一個我想使用RxJava加入的單獨線程池中執行。 使用Java 5構造的“舊”方式是這樣的(省略了收集結果):

final Future<Response> future1 = wsClient.callAsync();
final Future<Response> future2 = wsClient.callAsync();
final Future<Response> future3 = wsClient.callAsync();
final Future<Response> future4 = wsClient.callAsync();

future1.get();
future2.get();
future3.get();
future4.get();

這將阻塞我當前的線程,直到所有將來都完成為止,但是調用將並行進行,並且整個操作僅花費與最長調用相同的時間。

我想使用RxJava進行相同的操作,但是在如何正確建模方面我有點笨。

我嘗試了以下方法,它似乎可以工作:

Observable.from(Arrays.asList(1,2,3,4))
            .flatMap(n -> Observable.from(wsClient.callAsync(), Schedulers.io()))
            .toList()
            .toBlocking()
            .single();

這種方法的問題在於,我引入了Schedulers.io線程池,因為我已經在阻塞當前線程(使用toBlocking()),這會導致不必要的線程切換。 有什么方法可以對Rx流進行建模以並行執行任務,並阻塞直到所有任務完成?

您應該使用zip功能。 例如這樣:

Observable.zip(
        Observable.from(wsClient.callAsync(), Schedulers.io()),
        Observable.from(wsClient.callAsync(), Schedulers.io()),
        Observable.from(wsClient.callAsync(), Schedulers.io()),
        Observable.from(wsClient.callAsync(), Schedulers.io()),
        (response1, response2, response3, response4) -> {
            // This is a zipping function...
            // You'll end up here when you've got all responses
            // Do what you want with them and return a combined result
            // ...
            return null; //combined result instead of null
        })
        .subscribe(combinedResult -> {
            // Use the combined result
        });

Observable.zip也可以與Iterable一起使用,因此可以包裝Observable.from(wsClient.callAsync(), Schedulers.io()); 周圍有一個(返回其中的4個)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM