RxJava_distinct&distinctUntilChanged

weixin_33670713發表於2019-01-10

相同點

過濾發射的相同元素,對於物件需要實現equals方法

區別

  • distinctUntilChanged只確保相鄰元素不重複出現
  • distinct會過濾掉之前已發射的元素

distinctUntilChanged

@Test
fun distinct(){
    Observable.create<Int> {
                for (i in 0..3){
                   it.onNext(i)
                   it.onNext(i)
                }
                for (i in 0..3){
                   it.onNext(i)
                }
                it.onComplete() 
        }.distinctUntilChanged()
        .subscribeBy {
            System.out.print("$it ")
        }
      : 0 1 2 3 0 1 2 3

distinct

@Test
fun distinct(){
    Observable.create<Int> {
                for (i in 0..3){
                   it.onNext(i)
                   it.onNext(i)
                }
                for (i in 0..3){
                   it.onNext(i)
                }
                it.onComplete() 
        }.distinct()
        .subscribeBy {
            System.out.print("$it ")
        }
      : 0 1 2 3