Rxjava学习之过滤操作符 — distinct

四种操作格式:
1. distinct()
2. distinct(Func1)
3. distinctUntilChanged()
4. distinctUntilChanged(Func1))

1、distinct()

Distinct的过滤规则是:只允许还没有发射过的数据项通过。

在某些实现中,有一些变体允许你调整判定两个数据不同(distinct)的标准。还有一些实现只比较一项数据和它的直接前驱,因此只会从序列中过滤掉连续重复的数据。
这里写图片描述

  Observable.just(1,2,3,4,5,5,6)
        .distinct()
        .subscribe(integer -> Log.d("TAG","--->"+integer));

运行结果:
—>1
—>2
—>3
—>4
—>5
—>6

2、distinct(Func1)

这个操作符有一个变体接受一个函数。这个函数根据原始Observable发射的数据项产生一个Key,然后,比较这些Key。如果两个数据的key相同,则只保留最先到达的数据。

这里写图片描述

 Observable.just(1,2,3,true,4,10.0f,false,6.1f).distinct(item -> {
          if (item instanceof Integer) {
            return "I";
          }else if(item instanceof Boolean){
            return "B";
          }else {
            return "F";
          }
        }
    )
        .subscribe(
       integer-> Log.d("TAG", "distinct:"+integer));

运行结果:
distinct:1
distinct:true
distinct:10.0

3、distinctUntilChanged()

它只判定一个数据和它的直接前驱是否是不同的

这里写图片描述

 Observable.just(1,2,3,2,5,5,6).distinctUntilChanged()
        .subscribe(integer -> Log.d("TAG","--->"+integer));

运行结果:
—>1
—>2
—>3
—>2
—>5
—>6

4、distinctUntilChanged(Func1)

跟distinct(Func1)操作类似,但是判定的key是否和前驱重复。
这里写图片描述

 Observable.just(1,2,3,true,4,10.0f,false,6.1f).distinctUntilChanged(
        item -> {
          if (item instanceof Integer) {
            return "I";
          }else if(item instanceof Boolean){
            return "B";
          }else {
            return "F";
          }
        }
    )
        .subscribe(obj -> Log.d("TAG","--->"+obj));

运行结果:
—>1
—>true
—>4
—>10.0
—>false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值