Rxjava zip运算符过滤第二个Observable,通过第一个Observable android检查数据

时间:2017-06-14 05:12:36

标签: android filter rx-java rx-android

我正在使用.zip运算符来合并2 API calls

我想要什么

我希望根据2nd Observable

中的某些ids1st Observable获取过滤值

例如

1st Observable返回类似(示例数据)

的数据
"categories": [
{
            "category": "1",
            "category_name": "Wedding Venues",
            "category_photo_url": "http://www.marriager.com/uploads/album/0463373001465466151-0463467001465466151.jpeg",
            "category_type_id": "1",

2nd Observable返回如下数据:

"data": [
        {
            "cat_id": "1",
            "category_name": "Wedding Venues",
            "status": "1",
            "order_id": "1",
            "category_type_id": "1"
        },

我想过滤我的第二个Observable数据,只返回与1st Observable匹配 category_type_id 的值

我的代码

Observable obsService = retrofitService.loadService(getSharedPref().getVendorId());
Observable obsCategory = retrofitService.loadCategory();

Observable<ServiceAndCategory> obsCombined = Observable.zip(obsService.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()), obsCategory.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()), new Func2<ServiceModel, CategoryModel, ServiceAndCategory>() {
            @Override
            public ServiceAndCategory call(ServiceModel serviceModel, CategoryModel categoryModel) {
                return new ServiceAndCategory(serviceModel, categoryModel);
            }
        });
        obsCombined.observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io());

        obsCombined.subscribe(new Subscriber<ServiceAndCategory>() {
            @Override
            public void onCompleted() {


            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof UnknownHostException || e instanceof ConnectException) {
                    mPresenter.onNetworkError();
                } else if (e instanceof SocketTimeoutException) {
                    mPresenter.onTimeOutError();
                } else {
                    mPresenter.onServerError();
                }
            }

            @Override
            public void onNext(ServiceAndCategory model) {

                mPresenter.onSuccess(model);
            }
        });

修改

基本上我想apppy以下逻辑

this.categoryList = combinedModel.categoryModel.getData();
        serviceList = combinedModel.serviceModel.getData().getCategories();

        for (int i = 0; i < serviceList.size(); i++) {

            for (int j = 0; j < categoryList.size(); j++) {

                if (!serviceList.get(i).getCategoryTypeId().equals(categoryList.get(j).getCategoryTypeId())) {

                    categoryList.remove(j);

                }

            }

        }

1 个答案:

答案 0 :(得分:2)

您可以使用地图和列表以反应方式应用此过滤,首先将所有类别收集到地图,将所有服务收集到列表中,将它们压缩在一起,然后根据类别映射过滤服务列表:

Observable<HashMap<Integer, CategoryData>> categoriesMapObservable =
        obsCategory
                .flatMapIterable(CategoryModel::getData)
                .reduce(new HashMap<>(),
                        (map, categoryData) -> {
                            map.put(categoryData.getCategoryTypeId(), categoryData);
                            return map;
                        }
                );

Observable<List<ServiceData>> serviceListObservable = obsService
        .map(ServiceModel::getData);

Observable obsCombined =
        Observable.zip(
                categoriesMapObservable
                        .subscribeOn(Schedulers.io()),
                serviceListObservable
                        .subscribeOn(Schedulers.io()),
                Pair::new
        )
                .flatMap(hashMapListPair -> {
                    HashMap<Integer, CategoryData> categoriesMap = hashMapListPair.first;
                    return Observable.from(hashMapListPair.second)
                            .filter(serviceData -> categoriesMap.containsKey(serviceData.getCategoryTypeId()))
                                .toList();
                    }, (hashMapListPair, serviceDataList) -> new Pair<>(hashMapListPair.first.values(), serviceDataList));

输出结果取决于您,此处我在最后应用了flatMap()的选择器,它将创建一对CategoryData的集合和一个ServiceData的过滤列表,您可以当然,创建你需要的任何自定义对象。

我不确定你从中获得了多少,从复杂性的角度来看似乎更有效,假设HashMap是O(1),其中类别是N,服务是M,你有N + M(N构建地图,M迭代列表并查询地图),而你的天真实现将是N x M.

至于代码复杂性,我不确定是否值得,你可以在zip的末尾应用你的逻辑进行过滤,或者使用一些可能更有效地过滤的库。

P observerOn(AndroidSchedulers.mainThread(}是不必要的,所以我将其删除了。