How to clean up Rx Subscription and Observable to prevent memory leaks?

Viewed 3037

I'm working on a project that uses Rx Java subscriptions and observables frequently and I am very new to the concept. I was wondering what the best practice is for disposing of them. Currently I am just nulling out the subscriptions/observables in the doOnUnsubscribe() function as well as using takeUntil() with a PublishSubject to trigger a disconnect for the observables. Is this the proper way to clean up these references or is there a better way? Thanks!

1 Answers

When a subscription ends naturally, via onCompleted() or onError(), the subscription is cleaned up. If you use:

Subscription sub = observable.subscribe( value -> doSomeStuff() );

then calling sub.unsubscribe() will release the resources.

You can also use a CompositeSubscription to hold all of your outstanding subscriptions. When you perform clear() on the composite, then all contained subscriptions will be unsubscribed and removed; when you unsubscribe() from the composite, then all subscriptions contained will be unsubscribed, and then the composite subscription itself will be unsubscribed.

Nulling out resources may not do what you want nor is it needed, especially if there are multiple subscriptions.

Related