Retrofit and RxJava: How to combine two requests and get access to both results?

As I understand – you need to make a request based on result of another request and combine both results. For that purpose you can use this flatMap operator variant: Observable.flatMap(Func1 collectionSelector, Func2 resultSelector)

Returns an Observable that emits the results of a specified function to the pair of values emitted by the source Observable and a specified collection Observable.enter image description here

Simple example to point you how to rewrite your code:

private Observable<String> makeRequestToServiceA() {
    return Observable.just("serviceA response"); //some network call
}

private Observable<String> makeRequestToServiceB(String serviceAResponse) {
    return Observable.just("serviceB response"); //some network call based on response from ServiceA
}

private void doTheJob() {
    makeRequestToServiceA()
            .flatMap(new Func1<String, Observable<? extends String>>() {
                @Override
                public Observable<? extends String> call(String responseFromServiceA) {
                    //make second request based on response from ServiceA
                    return makeRequestToServiceB(responseFromServiceA);
                }
            }, new Func2<String, String, Observable<String>>() {
                @Override
                public Observable<String> call(String responseFromServiceA, String responseFromServiceB) {
                    //combine results
                    return Observable.just("here is combined result!");
                }
            })
            //apply schedulers, subscribe etc
}

Using lambdas:

private void doTheJob() {
    makeRequestToServiceA()
            .flatMap(responseFromServiceA -> makeRequestToServiceB(responseFromServiceA),
                    (responseFromServiceA, responseFromServiceB) -> Observable.just("here is combined result!"))
            //...
}

Leave a Comment