LoginSignup
6
3

More than 5 years have passed since last update.

[RxSwift]一つ前の値を取ってくる

Posted at

RxSwiftの流れに乗った一つ前の値を取ってきて比較したい時、

extension ObservableType where E : Equatable {
  typealias PreviousPairObserver = (previous: Self.E?, current: Self.E)
  func pickPrevious() -> RxSwift.Observable<PreviousPairObserver> {
    return scanCurrentAndPrevious().map({ PreviousPairObserver(previous: $0.first, current: $0.last!) })
  }

  private func scanCurrentAndPrevious() -> Observable<ArraySlice<Self.E>> {
    return scan([]) { (previous, current) in
      return Array(previous + [current]).suffix(2)
    }
  }
}

こんな感じのextensionを生やして取ってくれば

rx_index_receiver.pickPrevious().subscribe(onNext: { (previous: Int?, current: Int) in

}).addDisposableTo(rx_disposeBag)

こんな感じに使えて幸せ

RxSwift便利だけと何やっているか分からなくなるからこうやってまとめたほうがいいな…。

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3