Search code examples
rx-java2micronaut

RxJava: how to do a second api call if first is successful and then create a combinded response


This is what I want to do:

  1. call first rest API
  2. if first succeeds call seconds rest API
  3. if both are successful -> create an aggregated response

I'm using RxJava2 in Micronaut.

This is what I have but I'm not sure it's correct. What would happen if the first or second API call fails?

@Singleton
public class SomeService {
    private final FirstRestApi firstRestApi;
    private final SecondRestApi secondRestApi;

    public SomeService(FirstRestApi firstRestApi, SecondRestApi secondRestApi) {
        this.firstRestApi = firstRestApi;
        this.secondRestApi = secondRestApi;
    }

    public Single<AggregatedResponse> login(String data) {
        Single<FirstResponse> firstResponse = firstRestApi.call(data);
        Single<SecondResponse> secondResponse = secondRestApi.call();
        return firstResponse.zipWith(secondResponse, this::convertResponse);
    }

    private AggregatedResponse convertResponse(FirstResponse firstResponse, SecondResponse secondResponse) {
        return AggregatedResponse
                   .builder()
                   .something1(firstResponse.getSomething1())
                   .something2(secondResponse.getSomething2())
                   .build();
    }
}

Solution

  • This should be as simple as

    public Single<AggregatedResponse> login(String data) {
        return firstRestApi.call(data)
                 .flatMap((firstResponse) -> secondRestApi.call().map((secondResponse) -> {
                     return Pair.create(firstResponse, secondResponse);
                 })
                 .map((pair) -> {
                     return convertResponse(pair.getFirst(), pair.getSecond());
                 });
    }
    

    In which case you no longer need zipWith. Errors just go to error stream as usual.