Skip to content Skip to sidebar Skip to footer

Am I Using Flatmap Correctly To Merge Results From Multiple Api Calls?

I want to make multiple API calls (with three different queries) and merge the results and then display them in onNext(). It is working but I am concerned that flatMap is not ideal

Solution 1:

You can simply merge them if you don't care which one is returns first

Observable<List<WebResult>> observable =MainApplication.apiProvider.getApiProviderA.getWebResults("query1")
                .mergeWith(MainApplication.apiProvider.getApiProviderA.getWebResults("query2"))
                .mergeWith(MainApplication.apiProvider.getApiProviderA.getWebResults("query3"))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());

in onNext() you will get each result as it's own list, if you want to get the result when they are all done with all the results you can use

Observable<List<WebResult>> observable =Observable.zip(MainApplication.apiProvider.getApiProviderA.getWebResults("query1"), MainApplication.apiProvider.getApiProviderA.getWebResults("query2"), MainApplication.apiProvider.getApiProviderA.getWebResults("query3"), (webResults, webResults2, webResults3) -> {
            List<WebResult> allResults = new ArrayList<>();
            allResults.addAll(webResults);
            allResults.addAll(webResults2);
            allResults.addAll(webResults3);
            return allResults;
        });

And in onNext() you will get one emission with all the results added together

Solution 2:

With the help of elmorabea's answer, I came up with this solution using zip:

List<Observable<WebResultsResponse>> results = new ArrayList<>();
results.add(MainApplication.apiProvider.getApiProviderA.getWebResults("query1"));
results.add(MainApplication.apiProvider.getApiProviderA.getWebResults("query2"));
results.add(MainApplication.apiProvider.getApiProviderA.getWebResults("query3"));

Observable<List<WebResult>> observable =Observable.zip(results, new Function<Object[], List<WebResult>>() {
    @OverridepublicList<WebResult> apply(Object[] responses) throwsException {
        List<WebResult> allResults = new ArrayList<>();
        for(int i=0; i<responses.length; i++) {
            WebResultsResponse response = (WebResultsResponse)responses[i];
            if(response != null && response.getData() != null && response.getData().getResults() != null)
                allResults.addAll(response.getData().getResults());
        }
        return allResults;
    }
})
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io());

Post a Comment for "Am I Using Flatmap Correctly To Merge Results From Multiple Api Calls?"