我是RxJava的新手。我有一些返回Observables的Jersey RxJava客户端。我需要拨打一个电话来获取一些数据,这些数据将成为我接下来3次调用的输入。我希望这些调用是并行的。最后,我想在完成所有需要所有数据的调用后进行计算。以下是它的外观:
interface Service {
Observable<ResultA> callServiceA(InitialData input);
Observable<ResultB> callServiceB(ResultA resultA);
Observable<ResultC> callServiceC(ResultA resultA);
Observable<ResultD> callServiceD(ResultA resultA);
FinalResult simpleCalculation(ResultA a, ResultB b, ResultC c, ResultD d);
}
class MyClass{
@Autowired
ExecutorService myExecutorService;
Observable<FinalResult> myMethod(InitialData initialData){
/* Make call to ServiceA, get the results, then make calls to services B, C, and D in parallel (on different threads), finally perform simpleCalculation, and emit the result */
}
}
答案 0 :(得分:4)
flatMap()
和zip()
是你的朋友。
Observable<FinalResult> myMethod(InitialData initialData) {
return service
.callServiceA(initialData)
.flatMap(resultA -> Observable.zip(
service.callServiceB(resultA),
service.callServiceC(resultA),
service.callServiceD(resultA),
(resultB, resultC, resultD) ->
service.simpleCalculation(resultA, resultB, resultC, resultD))
);
}
使用return observable将如下所示:
Subscription subscription =
myMethod(new InitialData())
.subscribe(finalResult -> {
// FinalResult will end up here.
},
throwable -> {
// Handle all errors here.
});
答案 1 :(得分:0)
您可以使用flatMap进行同步调用,然后使用zip或merge发出多个调用,然后在完成后再次使用flatMap。