DistinctUntilChanged
Returns an observable sequence that contains only distinct contiguous elements according to equality operator.
1
2
3
4
5
6
7
8
9
public func distinctUntilChanged()
-> Observable<Element> {
return self.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) })
}
public func distinctUntilChanged<K>(_ keySelector: @escaping (Element) throws -> K, comparer: @escaping (K, K) throws -> Bool)
-> Observable<Element> {
return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer)
}
final private class DistinctUntilChangedSink<Observer: ObserverType, Key>: Sink, ObserverType
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
typealias Element = Observer.Element
private let _parent: DistinctUntilChanged<Element, Key>
private var _currentKey: Key?
func on(_ event: Event<Element>) {
switch event {
case .next(let value):
do {
// find the comparable `key` from `value`
let key = try self._parent._selector(value)
var areEqual = false
if let currentKey = self._currentKey {
// compare the `key` using comparer
areEqual = try self._parent._comparer(currentKey, key)
}
if areEqual {
return
}
self._currentKey = key
self.forwardOn(event)
}
catch let error {
self.forwardOn(.error(error))
self.dispose()
}
case .error, .completed:
self.forwardOn(event)
self.dispose()
}
}
final private class DistinctUntilChanged<Element, Key>: Producer
1
2
3
4
5
6
7
8
9
10
11
12
typealias KeySelector = (Element) throws -> Key
typealias EqualityComparer = (Key, Key) throws -> Bool
private let _source: Observable<Element>
fileprivate let _selector: KeySelector
fileprivate let _comparer: EqualityComparer
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = DistinctUntilChangedSink(parent: self, observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}