-
Notifications
You must be signed in to change notification settings - Fork 0
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.
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.
- CompositeSubscriptions are single use. Once unsubscribed they are dead and cannot be re-used.
- 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
- CompositeSubscriptions use hard references to all Subscriptions added to them.
- 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!
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.