When to call dispose and clear on CompositeDisposable

user4260260 picture user4260260 · Nov 1, 2017 · Viewed 19.7k times · Source

My question can be a duplicate of How to use CompositeDisposable of RxJava 2? But asking to clear one more doubt. According to the accepted answer

// Using clear will clear all, but can accept new disposable
disposables.clear(); 
// Using dispose will clear all and set isDisposed = true, so it will not accept any new disposable
disposables.dispose(); 

In my case, I'm using fragments as my views (View layer in MVP) and in some scenarios, I add active fragment to backstack, which actually does not kill the Fragment but only its view. Which means only onDestroyView is called and not the onDestroy . And later I can come back to the same fragment which is in the backstack, so only its view is being re-created. I have a CompositeDisposable as the member of my BaseFragment which holds subscriptions.

My question is, should I call clear on CompositeDisposable each time on onDestroyView? So that it can again take subscriptions once the view is resumed? And call dispose on the onDestroy, so that when the fragment itself is destroyed no need to take disposables anymore?

If it is wrong what is the proper way to handle. When clear and dispose have to be called.?

Answer

Jans picture Jans · Nov 1, 2017

You're right, you can save yourself from creating a new CompositeDisposable for each time the corresponding view is created, but instead treat a CompositeDisposable as a single instance tied to the onCreate/onDestroy lifecycle methods and treat aggregated disposables as part of the fragment view calling clear in onDestroyView.