如何忽略rxjava中的某些变换

时间:2016-05-10 08:17:38

标签: rx-java rx-android

如下面的示例代码,如果在flapMap中为true,我可以忽略一些转换并立即运行subscribe()。

 Observable.just("10+20", "123", "10x20", "10")
            .flatMap(new Func1<String, Observable<String>>() {
                @Override
                public Observable<String> call(String s) {
                    //if something true
                    //else continue next map
                    return null;
                }
            })
            .map(new Func1<String, String>() {
                @Override
                public String call(String s) {
                    //do something one
                    return null;
                }
            })
            .map(new Func1<String, String>() {
                @Override
                public String call(String s) {
                    //do something two
                    return null;
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<String>() {
                @Override
                public void call(String s) {
                    //end
                }
            });

是否可以这样做?

1 个答案:

答案 0 :(得分:0)

您可以在flatMap运算符

中嵌套转换
    Observable.just("10+20", "123", "10x20", "10")
            .flatMap(new Func1<String, Observable<String>>() {
                @Override
                public Observable<String> call(String string) {
                    if (condition) {
                        return Observable.just(string);
                    } else {
                        return Observable.just(string)
                                .map(new Func1<String, String>() {
                                    @Override
                                    public String call(String s) {
                                        //do something one
                                        return null;
                                    }
                                })
                                .map(new Func1<String, String>() {
                                    @Override
                                    public String call(String s) {
                                        //do something two
                                        return null;
                                    }
                                })
                    }
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<String>() {
                @Override
                public void call(String s) {
                    //end
                }
            });