如何使用 RxJava 和 RxAndroid 获取带条件的地图?

How to get Map with condition using RxJava2 and RxAndroid?

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

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

现在我需要做的是:

每个对象都有列表 servicePartList ,我需要按条件过滤这个列表,最终如果这个过滤列表的最终大小 >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()而且这样添加key也是不对的:

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

所以问题是如何正确制作它?

一种解决方案是使用 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();