【问题标题】:How to get Map with condition using RxJava2 and RxAndroid?如何使用 RxJava 和 RxAndroid 获取有条件的地图?
【发布时间】:2018-01-23 09:17:32
【问题描述】:

所以,我已经按照对象的条件列表进行了排序

private Observable<CallServiceCode> getUnansweredQuestionList() {
    return Observable.fromIterable(getServiceCodeArrayList())
               .subscribeOn(Schedulers.computation())
               .filter(iServiceCode -> iServiceCode.getServiceCodeFormStatus().isUnanswered());
}

现在我需要做什么:

每个对象都有列表servicePartList,我需要按条件过滤这个列表,最终如果这个过滤列表的最终大小&gt;0,所以我需要添加包含这个列表CallServiceCode object的对象作为键和这个过滤后的列表作为值。

所以应该是这样的:

private Map<CallServiceCode, ArrayList<CallServicePart>> getSortedMap() {
      Map<CallServiceCode, ArrayList<CallServicePart>> result = new HashMap<>();

      getUnansweredQuestionList()
          .filter(callServiceCode -> Observable.fromIterable(callServiceCode.getCallServicePartList()) //
          .filter(servicePart -> servicePart.getServicePartFormStatus().isUnanswered())//
          .isNotEmpty())
          .subscribe(callServiceCode -> result.put(callServiceCode, Observable.fromIterable(callServiceCode.getCallServicePartList()) //
                                                                                                .filter(servicePart -> servicePart.getServicePartFormStatus().isUnanswered()));
      return result;
}

但是 RxJava2 中没有 isNotEmpty() 这样的方法,而且这样添加密钥也是不对的:

Observable.fromIterable(callServiceCode.getCallServicePartList())
    .filter(servicePart -> servicePart.getServicePartFormStatus().isUnanswered())

那么问题是如何正确地制作它?

【问题讨论】:

    标签: java android rx-java rx-java2 rx-android


    【解决方案1】:

    一种解决方案是使用collect 直接从可观察对象创建Map

    return getUnansweredQuestionList()
            .collect(HashMap<CallServiceCode, List<CallServicePart>>::new,(hashMap, callServiceCode) -> {
                List<CallServicePart> callServiceParts = Observable.fromIterable(callServiceCode.getServicePartList())
                            .filter(s -> !s.getServicePartFormStatus().isUnanswered())
                            .toList().blockingGet();
                if (!callServiceParts.isEmpty())
                    hashMap.put(callServiceCode, callServiceParts);
            }).blockingGet();
    

    如果您将过滤提取到一个方法中(也可以是CallServiceCode 的成员),那么代码会更简洁:

    return getUnansweredQuestionList()
               .collect(HashMap<CallServiceCode, List<CallServicePart>>::new, (hashMap, callServiceCode) -> {
                   List<CallServicePart> filteredParts = getFilteredServiceParts(callServiceCode.getServicePartList());
                   if (!filteredParts .isEmpty())
                       hashMap.put(callServiceCode, filteredParts);
                }).blockingGet();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      • 2023-03-15
      • 2015-11-21
      • 2016-12-14
      • 2016-02-23
      • 1970-01-01
      相关资源
      最近更新 更多