How to leak memory with Disposables in RxJava2

Marcin Robaczyński
6 min readDec 17, 2019

There are plenty of great how-to articles about RxJava. It does simplify things significantly when working with Android framework but be careful because simplification may have its own pitfalls. In the following parts, you are going to explore one of them and see how easy it is to create a memory leak with RxJava2’s Disposables.

Solving simple task

Imagine that your product manager called in and asked you to create a widget which displays a random movie title. It has to be based on some external recommendation service. This widget should display a movie title on user’s demand or it could do it on its own. The manager also wants this widget to be able to store some information related to user’s interaction with it.

MVP-based approach is one of the many ways to do this. You create a simple view containing both ProgressBar and TextView widgets. The RecommendedMovieUseCase handles providing a random movie title.
Presenter connects to a use case and displays a title on a view. Saving presenter’s state is implemented by keeping it in memory even when your Activity is being recreated (in so-called NonConfigurationScope).

Here is how your Presenter looks like. For the purpose of this article, let’s assume that you want to store a flag indicating whether the…

--

--