据我了解 - 您需要根据另一个请求的结果发出请求并合并两个结果.为此,您可以使用此flatMap
运算符变体:Observable.flatMap(Func1 collectionSelector,Func2 resultSelector)
返回一个Observable,它将指定函数的结果发送到源Observable和指定集合Observable发出的值对.
简单的例子,指出如何重写代码:
private ObservablemakeRequestToServiceA() { return Observable.just("serviceA response"); //some network call } private Observable makeRequestToServiceB(String serviceAResponse) { return Observable.just("serviceB response"); //some network call based on response from ServiceA } private void doTheJob() { makeRequestToServiceA() .flatMap(new Func1 >() { @Override public Observable extends String> call(String responseFromServiceA) { //make second request based on response from ServiceA return makeRequestToServiceB(responseFromServiceA); } }, new Func2 >() { @Override public Observable call(String responseFromServiceA, String responseFromServiceB) { //combine results return Observable.just("here is combined result!"); } }) //apply schedulers, subscribe etc }
使用lambdas:
private void doTheJob() { makeRequestToServiceA() .flatMap(responseFromServiceA -> makeRequestToServiceB(responseFromServiceA), (responseFromServiceA, responseFromServiceB) -> Observable.just("here is combined result!")) //... }