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.

57 lines
1.6 KiB

5 years ago
  1. //
  2. // nwise.swift
  3. // RxSwiftExt
  4. //
  5. // Created by Zsolt Váradi on 09/12/2017.
  6. // Copyright © 2017 RxSwift Community. All rights reserved.
  7. //
  8. import RxSwift
  9. extension ObservableType {
  10. /**
  11. Groups the elements of the source observable into arrays of N consecutive elements.
  12. The resulting observable:
  13. - does not emit anything until the source observable emits at least N elements;
  14. - emits an array for every element after that;
  15. - forwards any error or completed events.
  16. For example:
  17. --(1)--(2)--(3)-------(4)-------(5)------->
  18. |
  19. | nwise(3)
  20. v
  21. ------------([1,2,3])-([2,3,4])-([3,4,5])->
  22. - parameter n: size of the groups, must be greater than 1
  23. */
  24. public func nwise(_ n: Int) -> Observable<[E]> {
  25. assert(n > 1, "n must be greater than 1")
  26. return self
  27. .scan([]) { acc, item in Array((acc + [item]).suffix(n)) }
  28. .filter { $0.count == n }
  29. }
  30. /**
  31. Groups the elements of the source observable into tuples of the previous and current elements.
  32. The resulting observable:
  33. - does not emit anything until the source observable emits at least 2 elements;
  34. - emits a tuple for every element after that, consisting of the previous and the current item;
  35. - forwards any error or completed events.
  36. For example:
  37. --(1)--(2)--(3)-------(4)-------(5)------->
  38. |
  39. | pairwise()
  40. v
  41. -------(1,2)-(2,3)----(3,4)-----(4,5)----->
  42. */
  43. public func pairwise() -> Observable<(E, E)> {
  44. return self.nwise(2)
  45. .map { ($0[0], $0[1]) }
  46. }
  47. }