Filter Observable <list <object>&gt;与另一个Observable <list <anotherobject>&gt;

时间:2017-08-29 19:17:24

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

有没有办法实现以下目标?

我有两个Observable,

  • Observable<List<String>> broadcastIdsObservable
  • Observable<List<EventData>> eventDatasObservable

有没有办法用broadcastIdsObsevable中的List过滤eventDatasObservable?我需要List<EventData> eventData满足条件eventData.getBroadcastId().equals(broadCastId),其中broadCastId是broadcastIds的每一项。

我尝试使用flatMap,map和Observable.concat的不同方法......但我无法实现它。

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以使用RxJavaJoins。你需要包括

compile 'io.reactivex:rxjava-joins:0.22.0'

然后创建Join:

@NonNull
@SuppressWarnings("unchecked")
private Func0<Observable<List<EventData>>> loadAndFilterEvents() {
    return new Func0<Observable<List<EventData>>>() {

        @Override
        public Observable call() {

            Observable<List<String>> broadcastIdsObservable = ...;
            Observable<List<EventData>> eventDatasObservable = ...;

            Plan0<List<EventData>> plan = JoinObservable.from(broadcastIdsObservable)
                                                        .and(eventDatasObservable)
                                                        .then(filterJoin);
            return JoinObservable.when(plan).toObservable();
        }

        private Func2<List<String>, List<EventData>, List<EventData>> filterJoin = (broadcastIds, events) -> {
            List<EventData> filtered = new ArrayList<>();
            for (EventData event : events) {
                if (broadcastIds.contains(event.getBroadcastId())) {
                    filtered.add(event);
                }
            }
            return filtered;
        };

    };
}

订阅它:

Observable.defer(loadAndFilterEvents())
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe(filteredEvents -> Timber.d("Events: %s", filteredEvents),
                         Timber::e);