Skip to content
This repository has been archived by the owner on Oct 22, 2021. It is now read-only.

DisposeBag

Ean Lombardo edited this page Jun 2, 2016 · 3 revisions

Javadoc

Why DisposeBag

UI development with RXJava can be awesome. RXJava makes it easy to bind every field on a screen to an ever changing Observable that keeps the user constantly updated with the latest data. Unfortunately though the user will at some point close your awesome reactive UI and that's when things get a bit tricky. All of those Subscriptions need to be killed, otherwise when the data changes the Subscriptions will be trying to update a dead UI, usually crashing you app.

The solution

CompositeSubscriptions allow you to add all of those Subscriptions into one easy to use Subscription that can be unsubscribed with one call. However, there are just a few problems with CompositeSubscriptions.

  1. CompositeSubscriptions are single use. Once unsubscribed they are dead and cannot be re-used.
  2. This means if you want to unsubscribe all Subscriptions when you UI suspends/minimizes, and re-create them when resumed, you have to build up a whole new CompositeSubscription
  3. CompositeSubscriptions use hard references to all Subscriptions added to them.
  4. This means that even if you Subscriber completes and nothing else references it, the CompositeSubscription will still reference it until the CompositeSubscription itself is unsubscribed. This means if you have a fairly long lived UI you could be leaking everything in the reference tree that is referenced by your Subscribers, and memory leaks are not fun!

The better solution

DisposeBag always references the Subscriptions it contains with WeakReferences and properly performs memory cleanup on every transaction. Its even re-usable! Simply add you subscribers and call disposeAll() on your DisposeBag, the DisposeBag can still have more Subscriptions added to it when your UI returns.

Clone this wiki locally