1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RxSwiftのObservableメソッドのメモ

Last updated at Posted at 2020-04-19

RxSwiftを学ぶ上でObservableメソッドとしていくつか現れてくるので、アウトプットとしてまとめたいと思います。

1. Observable

処理を記述する“起点”で、宣言しておくものと覚えておく。(理解が浅い)

2. from

Observableインスタンスを生成するためのメソッド。
fromの他にも、一つだけの要素を渡すjustや複数の要素を渡すofもある。

sample.swift
  // 1つの要素
  Observable.just("アップル")

  // 複数要素
  Observable.of("a", "b", "c", "d")

3. map

配列のmapと同様、加工ができる。
※mapやfromなどのメソッドを“Operator”と呼んでいるらしい。

Observable.mapの戻り値はObservableであり、以下がサンプルです。

sample.swift
  .map({ price in
      Int(price * tax)
  })

この状態だと、返り値はObservableになります。

4. subscribe

subscribeは購読という意味。
イメージとしては、subscribeを呼び出すことでmapやfromで記述した処理が動き出して、各要素がObserverに渡されていく。以下参考文献からの引用コードです。

sample.swift
  .subscribe(onNext: { [weak self] _ in
      self?.increment()
  })

クロージャで書くことができ、onNextはObserverに渡される時に呼び出される。

5. disposed

subscribeによって動作している処理を停止して、Observableが内部で保持しているObserverを開放するメソッド。
引数にインスタンス変数として定義したdisposeBagを入れることで、表示中のViewControllerが破棄(deinit)されたタイミングでdisposeBag自身もと購読が破棄される。

sample.swift
    @IBOutlet weak var countButton: UIButton!
    private let disposeBag: DisposeBag = DisposeBag()

    private func bindButtonToValue() {
        countButton.rx.tap
            .subscribe(onNext: { [weak self] _ in
                self?.increment()
            })
            .disposed(by: disposeBag)
    }

    func increment() {
       省略...
    }

所感

理解が難しい内容ほどアウトプットして理解を怠らないようにしなければならない。
rxの理解がまだまだなのでこれからもアウトプットして質を高めていく。

参考資料

http://open8tech.hatenablog.com/entry/2019/04/03/111100
https://www.2nd-walker.com/2020/01/30/beginning-of-rxswift-2/

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?