-
Notifications
You must be signed in to change notification settings - Fork 213
/
distinct.swift
69 lines (64 loc) · 2.5 KB
/
distinct.swift
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//
// distinct.swift
// RxSwiftExt
//
// Created by Segii Shulga on 5/4/16.
// Copyright © 2017 RxSwift Community. All rights reserved.
//
import Foundation
import RxSwift
extension Observable {
/**
Suppress duplicate items emitted by an Observable
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter predicate: predicate determines whether element distinct
- returns: An observable sequence only containing the distinct contiguous elements, based on predicate, from the source sequence.
*/
public func distinct(_ predicate: @escaping (Element) throws -> Bool) -> Observable<Element> {
var cache = [Element]()
return flatMap { element -> Observable<Element> in
if try cache.contains(where: predicate) {
return Observable<Element>.empty()
} else {
cache.append(element)
return Observable<Element>.just(element)
}
}
}
}
extension Observable where Element: Hashable {
/**
Suppress duplicate items emitted by an Observable
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
*/
public func distinct() -> Observable<Element> {
var cache = Set<Element>()
return flatMap { element -> Observable<Element> in
if cache.contains(element) {
return Observable<Element>.empty()
} else {
cache.insert(element)
return Observable<Element>.just(element)
}
}
}
}
extension Observable where Element: Equatable {
/**
Suppress duplicate items emitted by an Observable
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
*/
public func distinct() -> Observable<Element> {
var cache = [Element]()
return flatMap { element -> Observable<Element> in
if cache.contains(element) {
return Observable<Element>.empty()
} else {
cache.append(element)
return Observable<Element>.just(element)
}
}
}
}