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.

53 lines
1.9 KiB

5 years ago
  1. //
  2. // distinct+RxCocoa.swift
  3. // RxSwiftExt
  4. //
  5. // Created by Rafael Ferreira on 3/8/17.
  6. // Copyright © 2017 RxSwift Community. All rights reserved.
  7. //
  8. import RxCocoa
  9. extension SharedSequence {
  10. /**
  11. Suppress duplicate items emitted by an SharedSequence
  12. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
  13. - parameter predicate: predicate determines whether element distinct
  14. - returns: An shared sequence only containing the distinct contiguous elements, based on predicate, from the source sequence.
  15. */
  16. public func distinct(_ predicate: @escaping (Element) -> Bool) -> SharedSequence<SharingStrategy, Element> {
  17. var cache = [Element]()
  18. return flatMap { element -> SharedSequence<SharingStrategy, Element> in
  19. if cache.contains(where: predicate) {
  20. return SharedSequence<SharingStrategy, Element>.empty()
  21. } else {
  22. cache.append(element)
  23. return SharedSequence<SharingStrategy, Element>.just(element)
  24. }
  25. }
  26. }
  27. }
  28. extension SharedSequence where Element: Equatable {
  29. /**
  30. Suppress duplicate items emitted by an SharedSequence
  31. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
  32. - returns: An shared sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
  33. */
  34. public func distinct() -> SharedSequence<SharingStrategy, Element> {
  35. var cache = [Element]()
  36. return flatMap { element -> SharedSequence<SharingStrategy, Element> in
  37. if cache.contains(element) {
  38. return SharedSequence<SharingStrategy, Element>.empty()
  39. } else {
  40. cache.append(element)
  41. return SharedSequence<SharingStrategy, Element>.just(element)
  42. }
  43. }
  44. }
  45. }