You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.5 KiB

5 years ago
5 years ago
5 years ago
  1. //
  2. // distinct.swift
  3. // RxSwiftExt
  4. //
  5. // Created by Segii Shulga on 5/4/16.
  6. // Copyright © 2017 RxSwift Community. All rights reserved.
  7. //
  8. import Foundation
  9. import RxSwift
  10. extension Observable {
  11. /**
  12. Suppress duplicate items emitted by an Observable
  13. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
  14. - parameter predicate: predicate determines whether element distinct
  15. - returns: An observable sequence only containing the distinct contiguous elements, based on predicate, from the source sequence.
  16. */
  17. public func distinct(_ predicate: @escaping (Element) throws -> Bool) -> Observable<Element> {
  18. var cache = [Element]()
  19. return flatMap { element -> Observable<Element> in
  20. if try cache.contains(where: predicate) {
  21. return Observable<Element>.empty()
  22. } else {
  23. cache.append(element)
  24. return Observable<Element>.just(element)
  25. }
  26. }
  27. }
  28. }
  29. extension Observable where Element: Hashable {
  30. /**
  31. Suppress duplicate items emitted by an Observable
  32. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
  33. - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
  34. */
  35. public func distinct() -> Observable<Element> {
  36. var cache = Set<Element>()
  37. return flatMap { element -> Observable<Element> in
  38. if cache.contains(element) {
  39. return Observable<Element>.empty()
  40. } else {
  41. cache.insert(element)
  42. return Observable<Element>.just(element)
  43. }
  44. }
  45. }
  46. }
  47. extension Observable where Element: Equatable {
  48. /**
  49. Suppress duplicate items emitted by an Observable
  50. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
  51. - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
  52. */
  53. public func distinct() -> Observable<Element> {
  54. var cache = [Element]()
  55. return flatMap { element -> Observable<Element> in
  56. if cache.contains(element) {
  57. return Observable<Element>.empty()
  58. } else {
  59. cache.append(element)
  60. return Observable<Element>.just(element)
  61. }
  62. }
  63. }
  64. }