简体   繁体   中英

RxSwift DisposeBag usage in ViewController

I am new to the RxSwift framework. I am using disposables in my ViewController and I am adding disposables in a DisposeBag .

Where should I deallocate the DisposeBag in order to dispose of all disposables? In the controller's viewDidAppear or deinit ? Which method is safer?

If you declare your dispose bag as an instance variable of your view controller subclass, it will be deallocated automatically as soon as your view controller gets deallocated. That is, if it is not retained by something else as well.

What is the purpose of a Disposable

Disposables are here to represent a handle into the observable's subscription. When disposed, it cancels the observable's operation. The most straight forward example is a network request. When the disposable related to this request is disposed of, if the request did not complete, it is cancelled.

DisposeBag

Dispose bag gathers multiple diposables whose lifecycles should be related. When the bag gets disposed of, all the diposables within it are also disposed of.

Where does it make sense to dispose of a bag within a View Controller

Now that we know what the disposables actually do, the question we need to answer is no longer "where should I dispose of my bag", but "when does it make sense to cancel my subscriptions"?

And here the answer is really related to the use case : sometimes you'll want to stop any work if the view controller is not on screen anymore. In that instance, releasing the dispose bag within viewDidDisappear: is a good option. Other times, it is probably better to let the dispose bag get released in deinit (classes lifecycle will take care of this without you needing to override deinit though), in the instances where you would rather have the observable continue do its work even if the view controller is absent from the screen.

In conclusion, no method is safer than another, it only depends on your use case.

If you subscribe to your observables in the viewWillAppear function, then you should deinit your disposeBag in the viewDidDisappear function. If you subscribe to your observables in the viewDidLoad , then don't worry about it, the dispose bag will automatically dispose. This latter way is standard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM