LoginSignup
23
17

More than 5 years have passed since last update.

[RxSwift] 次のmapに任意のオブジェクトを渡す方法

Posted at

RxSwiftにて、複数の処理を連結して、特定の結果を得たい場合に
mapを複数連結させ、次のmapに任意のオブジェクトも付与して渡したい、というケースも多いと思います。
例えば、複数の非同期処理があって、それぞれ順番に実行し、必要な情報が全部揃ったら、最後の処理を実行する。というイメージです。

このような場合は、mapを利用することで実現出来ます。

create
    { (observer: AnyObserver<Int>) in

        observer.onNext(1)
        observer.onCompleted()
        return NopDisposable.instance
    }
    .flatMap { value in

        return create { (observer: AnyObserver<Int>) in

            observer.onNext(value)
            observer.onCompleted()
            return NopDisposable.instance
            }
            .map { ($0, 2) }
    }
    .map { value, value2 in

        return (value, value2, 3)
    }
    .subscribe { event in

        switch event {
        case .Next(let value1, let value2, let value3):
            print(value1, value2, value3)
        case .Error(let error):
            print(error)
        case .Completed:
            print("completed")
        }
}

出力

1 2 3

mapは Transforming Observables と定義されており、
イベントの流れの形状を変更する事に使えます。

Swiftではタプルが使えるため、このような記述が実現出来ています。
RxSwiftのmapはかなり便利なので、使用頻度は高くなりそうですね!

23
17
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
23
17