RxJava之过滤操作符的使用

过滤操作符也是在上游和下游之间插入,主要用来进行数据的过滤
主要实现过程如下:
在这里插入图片描述

1,filter操作符

 Observable.just("zhan","san","li","si")
                .filter(new Predicate<String>() {
                    @Override
                    public boolean test(String s) throws Exception {
                        //return true;//不过滤,默认全部都会答应
                        //return false;//就全部不打印
                        return true;
                    }
                }).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Log.d("MainActivity","accept:"+s);
            }
        });

2,take操作符

    //定时器,每个2秒执行一次
        Observable.interval(2,TimeUnit.SECONDS)
                .take(8)//增加执行次数达到8 停止下来
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        Log.d("MainActivity","accept:"+aLong);
                    }
                });

3,distinct操作符

主要用于过滤重复的数据

   //过滤重复的
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                emitter.onNext(1);
                emitter.onNext(1);
                emitter.onNext(2);
                emitter.onNext(1);
                emitter.onNext(3);
                emitter.onNext(3);
            }
        }).distinct()
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Log.d("MainActivity","accept:"+integer);
                    }
                });

4,elementAt(index,“defaultValue”)操作符的使用

指定过滤的内容,可以设置默认值,如果找不到就使用默认的值,发射给下游

 Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                emitter.onNext("zhangsan");
                emitter.onNext("李四");
                emitter.onNext("赵武");
                emitter.onNext("zhangsan");
            }
        }).elementAt(1,"zhasss")
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Log.d("MainActivity","accept:"+s);
                    }
                });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值