LoginSignup
25
25

More than 5 years have passed since last update.

RxSwift の Disposing を理解する

Posted at

RxSwift のサンプルコードを見ていると 次のようなコードがよく登場します。

        textField.rx_text
            .subscribeNext { [weak self] x in
                self?.debug("UITextField text \(x)")
                self?.textField.resignFirstResponder()
            }
            .addDisposableTo(disposeBag)

ReactiveCocoa にないメソッドなので 気になって調べました。

dispose とは

sequence をただちに中断するためのメソッドです。

https://github.com/ReactiveX/RxSwift/blob/master/Documentation/GettingStarted.md:

To cancel production of sequence elements and free resources immediatelly, call dispose on returned subscription.

書かないと メモリリークするの?

sequence が Complete もしくは Error を send すると リソースは開放されます。このあたりは ReactiveCocoa と同じですね。

When sequence sends Complete or Error event all internal resources that compute sequence elements will be freed.

なので 有限時間で完結する sequence は dispose しなくてもリークしないです。もちろん 完結しないと sequence はその間 リソースが確保されます。

If a sequence terminates in finite time, not calling dispose or not using addDisposableTo(disposeBag) won't cause any permanent resource leaks, but those resources will be used until sequence completes in some way (finishes producing elements or error happens).
If a sequence doesn't terminate in some way, resources will be allocated permanently unless dispose is being called manually, automatically inside of a disposeBag, scopedDispose, takeUntil or some other way.

というわけで 推奨としては dispose bags を使いましょう。

we recommend using them in production even though sequence will terminate in finite time.

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