简体   繁体   English

如何使用flatmap rxJava来执行并发任务

[英]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. 我抬起头来,我应该使用flatmap来做到这一点,但我不知道如何指导我。

getCompaniesData(pageNumber, perPage) // returns 100 companies getCompaniesData(pageNumber,perPage)//返回100家公司

getCompaniesData(pageNumber, perPage) //returns 100 companies getCompaniesData(pageNumber,perPage)//返回100家公司

Collate both responses - total 200 companies 整理两个回复 - 总共200家公司

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 目前这是我用params(1,100)返回的东西,一旦我得到数据我想用params(2,100)调用相同的函数,它给了我另一组数据并将它们组合起来并用它们做一些事情

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 谢谢R

Check first the docs of the flatMap operator, it says: 首先检查flatMap运算符的文档,它说:

transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable. 将Observable发出的项目转换为Observables,然后将这些项目的排放量变为单个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: 你可以提取方法getCompaniesData并以这种方式传递给它两个整数(或一个适当的类):

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. 您可以将运算符flatMap应用于定义方法发出的多个Observable

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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