LoginSignup
28
26

More than 5 years have passed since last update.

RxSwiftで開発中にハマった実装(Part 1)

Last updated at Posted at 2016-04-19

RxSwfitの開発で最近ハマったことをまとめてみた!(Part 1)

ここ最近の開発で詰まったあげく、解決するのに時間がかかってしまった実装についてまとめてみました

ホームのタブをタップした際、そのタブに今いたら最上部までスクロールする実装!

twitter.gif

twitterなどのタイムラインタブをタップするとトップにスクロールする実装!
必要なものは
・1つ前に表示されていたタブのインデックス
・今表示されているインデックス
。。。だけ

詰まったポイント -> どうやってpreviousIndexを取得するか!

はじめの実装

sample.swift
let currentIndex = Observable
    .of(
        homeButton.rx_tap.map { _ in 0 },
        notificationButton.rx_tap.map { _ in 1 },
        DMButton.rx_tap.map { _ in 2 }
    )
    .merge()
    .startWith(0)
    .shareReplay(1)

let previousIndex = currentIndex
    .takeLast(2)
    .take(1)

indexが流れているObservabletakeLast(2)で最新の2個を取得しtake(1)で古い方を取得できるんじゃないか!!



失敗

次に

sample.swift
let currentIndex = Observable
    .of(
        homeButton.rx_tap.map { _ in 0 },
        notificationButton.rx_tap.map { _ in 1 },
        DMButton.rx_tap.map { _ in 2 }
    )
    .merge()
    .startWith(0)
    .shareReplay(1)

let previousIndex = currentIndex
    .skip(1)

最新からskip(1)で一個スキップだ!!!



オペレーターの理解ミスwww

Screen Shot 2016-04-20 at 12.39.38 AM.png

はじめからn個をスキップ。

ここからが本番!
最初の一個飛ばしてindexをそろえて組み合わせれば!!!

sample.swift
let currentIndex = Observable
    .of(
        homeButton.rx_tap.map { _ in 0 },
        notificationButton.rx_tap.map { _ in 1 },
        DMButton.rx_tap.map { _ in 2 }
    )
    .merge()
    .startWith(0)
    .shareReplay(1)

Observable
    .zip(currentIndex, currentIndex.skip(1)) { $0 }
    .subscribeNext { (currentIndex, previsouIndex) in
        ...
    }
    .addDisposableTo(disposeBag)

これでskip(1)をして最初の1個を飛ばしたcurrentIndexのストリームを普通のcurrentIndexのストリームと
index をそろえてペアに!

Screen Shot 2016-04-20 at 12.43.53 AM.png

今の状態だと、画像上の黄色のAがない感じで一個手前にずれます!
なので、青の1と黄色のBがくっつきます!
これで無事今のindexと1つ前のindexを取得できて、ちゃんちゃん!

あとはfilter { $0.0 == $0.1 }subscribeNext{}の前に入れてあげると、Twitterのように、タイムラインにいる状態で、再度タイムラインタブをタップしたという状況だけで、なにかアクションを起こすことができます!

Part 2ではrx_notificationでのキーボード処理でハマったことをまとめます!!

28
26
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
28
26