Best Practices for Disposal Completed, Single, Possibly and Completing Observations in RxJava

I ask this from an Android perspective, but this should apply to RxJava in general.

As a best practice, should my view always delete even short-lived Completable , Single , Maybe and ending with Observable Rx types, which should end in short order, but can still be executed when the user closes the view? I know that when the Rx chain ends, it is deleted, but this may happen sometime after closing the view.

For example, Single executing an HTTP GET. The call ends, but may be after the destruction of a species that temporarily prevents garbage collection.

And if a CompositeDisposable used to collect such a Disposable in a long-lasting view, would I think it should take care of clear() or otherwise remove these Disposable regularly to prevent an unlimited growth in size of the CompositeDisposable ?

+8
android rx-java dispose rx-java2
source share
2 answers

As a best practice, should my view always delete even short-lived Completable, Single, Maybe and terminating Observable Rx types

If you share the code with others, as a best practice, I'm going to say yes, you have to dispose . Although this may seem like an additional stove for the boiler, it will prevent the next developer from trying to connect your subscription code and try to access components that can no longer exist (i.e. Context after disconnecting Fragment ... etc.).

And if CompositeDisposable is used to collect such Disposables in a long-lasting view, I think that care should be taken to clean () or otherwise remove these Disposables regularly to prevent the CompositeDisposable from growing unlimitedly?

I want to note that in rxjava2, CompositeDisposable is state; after calling dispose() , any subsequent Disposable added will be immediately deleted. So, as a best practice:

  • create a new CompositeDisposable at the beginning of the life cycle ( onCreate(...) , etc.)
  • take care of dispose() in onDestroy(...) , because by that time your callback is practically onDestroy(...) and just holds resources.
+6
source share

It is recommended that you avoid CompositeDisposable in onPause or onDestroy to avoid such problems.

+3
source share

All Articles