Rxjava 2结合最大错误

时间:2018-06-06 09:12:03

标签: android rx-java reactive-programming rx-java2 observer-pattern

我想收集两个方法调用的第一个发射,这可以使用combineLatest的Rxjava 2实现,但我对语法感到困惑

    Observable<Boolean> buildUseCaseObservable(Params params) {
    List<Observable> list = new ArrayList<>();        
    list.add(this.userRepository.fetchUserData());
    list.add(this.masterDataRepository.fetchLov());

    //I think the problem is in the syntax
    return Observable.combineLatest(list, new BiFunction<Boolean, Boolean, Boolean>() {
        @Override
        public Boolean apply(Boolean aBoolean, Boolean aBoolean2) throws Exception {
            System.out.println("FetchRegistrationData complete " + aBoolean + " " + aBoolean2);
            return aBoolean && aBoolean2;
        }
    });

    /* this works fine but it waits for onComplete() of both calls
    return Observable.zip(
            this.userRepository.fetchUserData(),
            this.masterDataRepository.fetchLov(),
            new BiFunction<Boolean, Boolean, Boolean>() {
                @Override
                public Boolean apply(@NonNull Boolean aBoolean, @NonNull Boolean aBoolean2) throws Exception {
                    System.out.println("FetchRegistrationData complete " + aBoolean + " " + aBoolean2);
                    return aBoolean && aBoolean2;
                }
            });*/
     }

1 个答案:

答案 0 :(得分:0)

您可以使用take()运算符限制可观察量的数量。这意味着一旦两个observable都发出一个值,combinerFunction将计算一个结果,并且observable将完成。

return Observable.combineLatest(
  this.userRepository.fetchUserData().take(1),
  this.masterDataRepository.fetchLov().take(1),
  combinerFunction)