RxSwift and the Secret of the Variadic DisposeBag
Use one of RxSwift’s newest features to dramatically clean up your code
My company has been using RxSwift for all new iOS projects for a while now, and we’ve come to appreciate it’s power, flexibility, and conciseness.
That said, there is one area where RxSwift is, shall we say, somewhat less than concise. Where, in point of fact, it’s downright redundant.
So today, let’s talk about Disposables and DisposeBags.
Disposables and DisposeBags?
As I’m sure you’re aware, Disposables and DisposeBags are RxSwift’s concession to Swift’s ARC memory management.
When you subscribe or bind to or drive from a RxSwift Observable, that subscription returns a Disposable. That disposable is basically a reference to that subscription and to that subscription’s entire Observable chain.
Until that disposable is disposed, the subscription chain exists (unless the subscription receives a completed or error event, but that’s another story).
So. Bottom line is that subscriptions return disposables which we need to maintain in order to properly control the lifecycle of the subscription.
Those disposables, for the sake of convenience, are usually inserted into a DisposeBag that’s been created and attached to a UIViewController (or in some cases to a View Model or other object).
And a DisposeBag is exactly what it says it is, a bag (or collection) of disposables.
So how does that help us?
Well, when the view controller is deallocated, its variables (including the bag) are deallocated. When the disposeBag is deallocated, its deinit function calls dispose on all of the disposables it contains.
Those disposables, in turn, release any references they may have to any observables they’re observing which may also, in turn, release their references to their observables, and so on, and so on, up the chain until we’re done.
Everything is properly released, nothing has leaked, and everyone is happy.
Except for one minor problem.
So, let’s say you’re using RxSwift and that you’re using a MVVM (Model-View-ViewModel) architecture.