RxSwift 操作符 (distinctUntilChanged)

distinctUntilChanged

ReactiveX:
The Distinct operator filters an Observable by only allowing items through that have not already been emitted.

移除相邻两个相同的元素。

pb1
    .distinctUntilChanged()
    .subscribe(onNext: { int in
        print("element: ", int)
    }).disposed(by: bag)

pb1.onNext(1)
pb1.onNext(1)
pb1.onNext(2)
pb1.onNext(3)
pb1.onNext(4)
pb1.onNext(4)
pb1.onNext(5)
pb1.onNext(6)
pb1.onCompleted()

输出:
1
2
3
4
5
6

把相邻的相同的都忽略掉了

distinctUntilChanged(: comparer)

Returns an observable sequence that contains only distinct contiguous elements according to the comparer.

根据自己定义的函数来过滤掉相邻的元素其中的一个。

pb1
    .distinctUntilChanged { $0 < $1 }
    .subscribe(onNext: { int in
        print("element: ", int)
    }).disposed(by: bag)

pb1.onNext(1)
pb1.onNext(1)
pb1.onNext(2)
pb1.onNext(3)
pb1.onNext(4)
pb1.onNext(4)
pb1.onNext(5)
pb1.onNext(6)
pb1.onCompleted()

输出:
1
1

其实distinctUntilChanged就是==的操作,<是因为第一个数比第二个数小,所以才会返回1,1。如果是>则返回:1,1,2,3,4,4,5,6,说白了就是过滤掉你的函数里返回true的数据。

阅读更多
想对作者说点什么?
相关热词

博主推荐

换一批

没有更多推荐了,返回首页