简体   繁体   中英

How to use a flatmap rxJava to perform concurrent task

I want to call a function twice with different parameters and the function returns set of values based on parameters. I want to collate both results and do something with it.

I looked up and I should be using flatmap to do that, but I am not sure how to.can you guide me on it please.

getCompaniesData(pageNumber, perPage) // returns 100 companies

getCompaniesData(pageNumber, perPage) //returns 100 companies

Collate both responses - total 200 companies

Do something with it.

Currently this is what I have which returns with params (1,100), Once I get the data I want to call the same function with params (2,100) which gives me another set of data and combine them both and do something with them

mHighLightsPresenter. getCompaniesData(1, 1000).doOnNext(fetchCompaniesResponse -> {
                    if(fetchCompaniesResponse != null)
                    {
                        List<com.dopay.onboarding.data.bean.Company> companies = fetchCompaniesResponse.getCompanies();
                        if (companies != null && !companies.isEmpty()) {
                            showCompaniesDialog(companies);
                        }

                        Toast.makeText(getContext(), "companies response is not null", Toast.LENGTH_LONG).show();
                    }
                }).subscribe();

Your suggestions are very helpful

Thanks R

Check first the docs of the flatMap operator, it says:

transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable.

How can I call the same function with different params?

You can extract the method getCompaniesData and pass to it two integers (or a proper class), in this way:

Observable<T> getCompaniesData(Param param);

How can I combine the different results?

You can apply the operator flatMap to the multiple Observable s emitted by the defined method.

Observable<T> foo(Param... params) {
    return Observable.fromArray(params)
        .flatMap(this::getCompaniesData)
        ...

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM