RxJava过滤器运算符

时间:2017-02-04 12:19:33

标签: java android rx-java observable rx-android

我是rxJava的新手。

好吧,我正在测试几个例子来集成rxJava中的运算符。 所以,我有一个问题:

    Observable.just("JUAN", "LUCILA", "ARMANDO").map(new Function<String, Integer>() {
        @Override
        public Integer apply(String s) throws Exception {
            return s.length();
        }
    }).all(new Predicate<Integer>() {
        @Override
        public boolean test(Integer integer) throws Exception {
            return integer > 0;
        }
    }).filter(new Predicate<Boolean>() {
        @Override
        public boolean test(Boolean aBoolean) throws Exception {
            return aBoolean;
        }
    }).subscribe(new Observer<Boolean>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(Boolean value) {
            Log.d("STATUS: ", "OK");
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {
            Log.d("STATUS: ", "COMPLETE");
        }
    })

因此,AndroidStudio标记我订阅时出错(新观察者)。 我的目标是将名称转换为长度的数字,所以我希望有一个条件,显然它会是真的,而且很晚,从过滤器中过滤掉TRUE,然后向我显示一条日志消息,说好了!

我希望你能帮助我! 谢谢!

1 个答案:

答案 0 :(得分:1)

http://reactivex.io/RxJava/2.x/javadoc/

处查看Single

正如评论Observable.all(...)中所述,您有Single类型,然后来自Single.filter(...),您的类型为Maybe

因此,您需要使用toObservable()然后订阅。

@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Maybe<T> filter(Predicate<? super T> predicate) {
    ObjectHelper.requireNonNull(predicate, "predicate is null");
    return RxJavaPlugins.onAssembly(new MaybeFilterSingle<T>(this, predicate));
}

`

更改为

Observable.just("JUAN", "LUCILA", "ARMANDO").map(new Function<String, Integer>() {
            @Override
            public Integer apply(String s) throws Exception {
                return s.length();
            }
        }).all(new Predicate<Integer>() {
            @Override
            public boolean test(Integer integer) throws Exception {
                return integer > 0;
            }
        }).filter(new Predicate<Boolean>() {
            @Override
            public boolean test(Boolean aBoolean) throws Exception {
                return aBoolean;
            }
        }).toObservable().subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean value) {
                Log.d("STATUS: ", "OK");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                Log.d("STATUS: ", "COMPLETE");
            }
        });