Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. // there are a couple of hidden, nasty error conditions
  2. // there's an assumption that the observable/driver returned from the
  3. // accumulator returns exactly 1 event (no more, no less)
  4. // really, it should return a Promise instead of an Observable
  5.  
  6. extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy {
  7. func scanDriver<A>(_ seed: A,
  8. accumulator: @escaping (A, Self.E) -> Driver<A>) -> Driver<A> {
  9. let scanner: Driver<Driver<A>> = self
  10. .scan(Driver.just(seed),
  11. accumulator: { (previousDriver: Driver<A>, current: Self.E) -> Driver<A> in
  12. return previousDriver
  13. .flatMap { previous in accumulator(previous, current) }
  14. // this seems a bit awkward -- should shareReplay be
  15. // available on Driver?
  16. .asObservable()
  17. .shareReplay(1)
  18. .asDriver(onErrorJustReturn: seed)
  19. })
  20. return scanner.flatMap { driver in driver }
  21. }
  22.  
  23. func scanDriverSubject<A>(_ seed: A,
  24. accumulator: @escaping (A, Self.E) -> Driver<A>) -> Driver<A> {
  25. let outVariable: Variable<A> = Variable(seed)
  26. let out: Driver<Driver<A>> = self.withLatestFrom(
  27. outVariable.asDriver(),
  28. resultSelector: { (next: Self.E, previous: A) -> Driver<A> in
  29. accumulator(previous, next)
  30. .do(onNext: { value in outVariable.value = value })
  31. })
  32. return out.flatMap { (dr: Driver<A>) -> Driver<A> in dr }
  33. }
  34. }
  35.  
  36. extension Observable {
  37. func scanObservable<A>(_ seed: A,
  38. accumulator: @escaping (A, Element) -> Observable<A>) -> Observable<A> {
  39. let scanner: Observable<Observable<A>> = self
  40. .scan(Observable<A>.just(seed),
  41. accumulator: { (previousObservable: Observable<A>, current: Element) -> Observable<A> in
  42. return previousObservable
  43. .flatMap { previous in accumulator(previous, current) }
  44. .shareReplay(1)
  45. })
  46. return scanner.flatMap { obs in obs }
  47. }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement