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).