RXJava 2.0 操作符的使用

public class RxjavaXU {
    @Test
    public void Flowable() throws Exception {
        //背压使用
        Flowable.create(new FlowableOnSubscribe<Integer>() {
            @Override
            public void subscribe(FlowableEmitter<Integer> e) throws Exception {
                for (int i = 0; i < 1000000000; i++) {
                    e.onNext(i);
                }

            }
            //背压的模式
            /**
             * * MISSING
             顾名思义,就是当你上游一股脑的抛下来很多东西的时候,我就只接一部分,其他的我都miss掉。
             * ERROR
             当下游无法再继续接受请求的时候会抛出异常MissingBackpressureException
             上游,你拼命抛吧,我这边要是拿不下了,我就报警,老子不干了!
             * BUFFER
             上游不断的发出onNext请求,直到下游处理完
             上游,你抛吧,我就屯着,实在不行了,系统崩溃,咱俩同归于尽
             * DROP
             如果下游已经溢出了,会丢弃掉溢出了的onNext请求。
             上游,你就拼命抛吧,我这里就拿那么多,我处理完了我再去你最新的里面拿
             * LATEST
             如果下游已经溢出了,会丢弃掉溢出了的onNext请求,但是会在内部缓存一个最新的onNext请求,在下一次请求的时候会把这个最新的先返回出去。
              有,任何形式的转载都请联系作者获得授权并注明出处。
             */
        }, BackpressureStrategy.BUFFER).subscribe(new Subscriber<Integer>() {
            @Override
            public void onSubscribe(Subscription s) {
                s.request(100);

            }

            @Override
            public void onNext(Integer integer) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(integer);
            }

            @Override
            public void onError(Throwable t) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    //---------转换操作符--------------------------------------


    @Test
    public void empty() throws Exception {
        Observable.empty()
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        System.out.println("直接调用");
                    }
                });
    }

    @Test
    public void map() throws Exception {
        Observable.just("111")
                .map(new Function<String, Integer>() {
                    @Override
                    public Integer apply(String s) throws Exception {
                        return 1;
                    }
                }).subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer bitmap) {
                System.out.println(bitmap);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Test
    public void flatMap() throws Exception {

        Observable.just("getToken", "login")
                .flatMap(new Function<String, ObservableSource<?>>() {
                    @Override
                    public ObservableSource<?> apply(String s) throws Exception {
                        //执行完下面的以后才往下执行,没有执行完不会往下执行
                        return creatRespence(s);
                    }
                }).subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object o) {
                System.out.println(o.toString());
            }


            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }

    private ObservableSource<?> creatRespence(final String s) {

        return Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                Thread.sleep(2000);
                e.onNext("登录" + s);
            }
        });
    }

    @Test
    public void groupBy() throws Exception {
        //分书的例子
        Observable.just(1, 2, 3, 4, 5)
                .groupBy(new Function<Integer, String>() {
                    @Override
                    public String apply(Integer integer) throws Exception {
                        return integer > 2 ? "A类书籍" : "B类书籍";
                    }
                })
                .subscribe(new Consumer<GroupedObservable<String, Integer>>() {
                    @Override
                    public void accept(final GroupedObservable<String, Integer> stringIntegerGroupedObservable) throws Exception {
                        stringIntegerGroupedObservable.subscribe(new Consumer<Integer>() {
                            @Override
                            public void accept(Integer integer) throws Exception {
                                String key = stringIntegerGroupedObservable.getKey();
                                System.out.println(key + integer);

                            }
                        });
                    }
                });
    }

    @Test
    public void range() throws Exception {
        //数据累加
        Observable.range(1, 10)
                .scan(new BiFunction<Integer, Integer, Integer>() {
                    @Override
                    public Integer apply(Integer integer, Integer integer2) throws Exception {
                        return integer + integer2;
                    }
                })
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer integer) {
                        System.out.println(integer);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    @Test
    public void buffer() throws Exception {
        //如果你有10000条数据要插入数据库,你慢慢插,时间太久,可以使用,多少条插入一次
        Observable.just(1, 2, 3, 4, 5, 6)
                .buffer(5)//5条插入一次
                .subscribe(new Observer<List<Integer>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(List<Integer> integers) {
                        System.out.println(integers);
                    }

                    @Override
                    public void onError(Throwable e) {


                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //---------过滤操作符--------------------------------------


    @Test
    public void Filter() throws Exception {
        Observable.just(1, 2, 3, 4, 5)
                //过滤操作符
                .filter(new Predicate<Integer>() {
                    @Override
                    public boolean test(Integer integer) throws Exception {
                        //大于2的才要
                        if (integer > 2) {
                            return true;
                        }
                        return false;
                    }
                }).subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer integer) {
                System.out.println(integer);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }

    @Test
    public void take() throws Exception {
        //每隔一秒钟 ,时间单位
        //这个API要RXAndroid 才有效果
        Observable.interval(1, TimeUnit.SECONDS)
                .take(5)//控制数量,超过5个执行onComplete  完成
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        System.out.println("onSubscribe");
                    }

                    @Override
                    public void onNext(Long aLong) {
                        System.out.println(aLong);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        System.out.println("完成");
                    }
                });
    }

    @Test
    public void distinct() throws Exception {
        //去除重复的元素
        Observable.just(1, 2, 2, 4, 5, 3, 4, 5, 6)
                .distinct()//去重
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer integer) {
                        System.out.println("--->" + integer);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @Test
    public void elementAt() throws Exception {
        Observable.just(1, 2, 2, 4, 5, 3, 4, 5, 6)
                .elementAt(5)//过滤了重复的之后,只处理第五个
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        //本来是1,2,4,5,3,6
                        System.out.println(integer);//打印3
                    }
                });
    }

    //------------条件操作符----------------------


    @Test
    public void All() throws Exception {
        Observable.just(1, 2, 3, 4, 5)
                .all(new Predicate<Integer>() {
                    @Override
                    public boolean test(Integer integer) throws Exception {
                        return integer > 2;//里面的东西全部都大于2,有一个不满足都false
                    }
                }).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                System.out.println(aBoolean);
            }
        });

    }

    @Test
    public void contains() throws Exception {
        Observable.just(1, 2, 3, 4, 5, 6)
                .contains(3)//里面的数据是否有3,是就true
//                .any(new Predicate<Integer>() {
//                    @Override
//                    public boolean test(Integer integer) throws Exception {
//                        return integer == 3;//与contains一样的,里面可以写逻辑
//                    }
//                })
//                .isEmpty()//是否有时间
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        System.out.println(aBoolean);
                    }
                });
    }

    @Test
    public void skipWhile() throws Exception {
        //要在android下执行,才有效果
        //                       开始     结束       延时多久发      间隔多久执行下一个时间
        Observable.intervalRange(0, 5, 1, 100, TimeUnit.MILLISECONDS)
                .skipWhile(new Predicate<Long>() {
                    @Override
                    public boolean test(Long aLong) throws Exception {
                        return aLong < 2;//少于2,不下发处理,注意:如果是true,不下发处理
                    }
                })//调过一段数据
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        System.out.println(aLong);//1,2小于上面的条件不处理,结果为:3,4,5
                    }
                });
    }


    //-------------合并操作符-------------------


    @Test
    public void startWith() throws Exception {

        Observable.just(1, 2, 3, 4, 5, 6)
                //先发送他的数据,中间插入数据
                .startWith(Observable.just(2, 3, 1, 2, 3, 9))
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        System.out.println(integer);
                    }
                })
        ;
    }

    @Test
    public void collect() throws Exception {
        //最多加入4个Observable,超过了就不行了
        Observable.concat(Observable.just(1, 2, 3)
                , Observable.just(4, 5, 6))
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        System.out.println(integer);
                    }
                });
    }

    @Test
    public void merge() throws Exception {
        Observable<Integer> just1 = Observable.just(1, 2, 3);
        Observable<Integer> just2 = Observable.just(4, 5, 6);
        Observable<Integer> just3 = Observable.just(7, 8, 9);
        //按照里面的顺序执行
        Observable.merge(just1, just2, just3).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {
                System.out.println(integer);//123456789
            }
        });

        //下面延时,并行执行 需要android  执行
//        Flowable.merge(Flowable.intervalRange(1, 5, 1000, 100, TimeUnit.MILLISECONDS),
//                Flowable.intervalRange(6, 10, 1000, 100, TimeUnit.MILLISECONDS))
//                .subscribe(new Consumer<Long>() {
//                    @Override
//                    public void accept(Long o) throws Exception {
//                        System.out.println(o);
//                    }
//                });

    }

    @Test
    public void mergeDelayError() throws Exception {
        //如果中途有发生错误,延时执行
        Flowable.mergeDelayError(
                Flowable.create(new FlowableOnSubscribe<Publisher<?>>() {
                    @Override
                    public void subscribe(FlowableEmitter<Publisher<?>> e) throws Exception {
                        e.onError(new NullPointerException());//延迟抛异常
                    }
                }, BackpressureStrategy.BUFFER)
                , Flowable.intervalRange(1, 5, 1000, 100, TimeUnit.MILLISECONDS))
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        System.out.println(o.toString());
                    }
                });
    }

    @Test
    public void zip() throws Exception {
        Flowable.zip(
                Flowable.just(1, 2, 3)//
                , Flowable.just(4, 5, 6)
                , Flowable.just(4, 3)//如果数量不同
                , new Function3<Integer, Integer, Integer, Integer>() {
                    @Override
                    public Integer apply(Integer integer, Integer integer2, Integer integer3) throws Exception {
                        return integer + integer2 + integer3;
                    }
                }).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {
                System.out.println(integer);//如果上面的数据长度不同,最后一个不处理
            }
        });
    }

    //-----错误操作符---------------


    @Test
    public void onErrorALL() throws Exception {
        Flowable.create(new FlowableOnSubscribe<String>() {
            @Override
            public void subscribe(FlowableEmitter<String> e) throws Exception {
                for (int i = 0; i < 10; i++) {
                    if (i == 2) {
                        e.onError(new Throwable("出现错误"));
                    } else {
                        e.onNext(i + "");
                    }
                }
            }
        }, BackpressureStrategy.BUFFER)
                .onErrorReturn(new Function<Throwable, String>() {
                    //当出现错误的时候可以返回一个结果弥补一下,然后立马停止往下执行
                    @Override
                    public String apply(Throwable throwable) throws Exception {
                        Log.e("----", "处理错误信息:" + throwable.toString());
                        //上面发生异常,返回一个弥补的结果
                        return "弥补错误的结果";
                    }
                }).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Log.e("----", "正确的数据:" + s);

            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Log.e("----", "出现错误的数据》》" + throwable.getMessage());
            }
        });


        Flowable.create(new FlowableOnSubscribe<String>() {
            @Override
            public void subscribe(FlowableEmitter<String> e) throws Exception {
                for (int i = 0; i < 10; i++) {
                    if (i == 2) {
                        e.onError(new Throwable("出现错误"));
                    } else {
                        e.onNext(i + "");
                    }
                }
            }
        }, BackpressureStrategy.BUFFER)
                .onErrorResumeNext(new Function<Throwable, Publisher<? extends String>>() {
                    @Override
                    public Publisher<? extends String> apply(Throwable throwable) throws Exception {
                        Log.e("----", "处理错误信息:" + throwable.toString());
                        //上面发生异常(使用下面的备用方案)
                        return Flowable.just("从新定义1个发源", "从新定义2个发源", "从新定义3个发源");
                    }
                }).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Log.e("----", "正确的数据:" + s);
            }
        });

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                for (int i = 0; i <= 5; i++) {
                    if (i == 2) {
                        //注意这里是Exception
                        e.onError(new Exception("出现错误了"));
                    } else {
                        e.onNext(i + "");
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                e.onComplete();
            }
        }).onExceptionResumeNext(new Observable<String>() {
            @Override
            protected void subscribeActual(Observer<? super String> observer) {
                observer.onNext("替换出现错误的信息");
                observer.onComplete();
            }
        }).subscribe(new io.reactivex.functions.Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Log.e("---", "--》》" + s);
            }
        });


        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                for (int i = 0; i <= 9; i++) {
                    if (i == 2) {
                        e.onError(new Exception("出现错误了"));
                    } else {
                        e.onNext(i + "");
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

                e.onComplete();
            }
        }).subscribeOn(Schedulers.newThread())
//            .retry(new Predicate<Throwable>() {
//            @Override
//            public boolean test(Throwable throwable) throws Exception {
//                Log.e("--", "retry错误: "+throwable.toString());
                    //返回假就是不让重新发射数据了,调用观察者的onError就终止了。
                    //返回真就是让被观察者重新发射请求
//                return false;
//            }
//        })
//             .retry(new BiPredicate<Integer, Throwable>() {
//                 @Override
//                 public boolean test(Integer integer, Throwable throwable) throws Exception {
//                     //integer错误次数
//                     Log.e("--", "retry错误: "+integer);
//                     return true;
//                 }
//             })
                //重连第几次
                .retry(3, new Predicate<Throwable>() {
                    @Override
                    public boolean test(Throwable throwable) throws Exception {

                        return true;
                    }
                })
                .subscribeOn(Schedulers.newThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Log.e("--", "收到消息: " + s);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Log.e("--", "结果错误: " + throwable.toString());
            }
        });


    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值