Leaking with Observables

As it happens, it is quite easy to leak memory when using Observables. Usually, Observables have access to the Activity instance because, at some point, it has to update the UI with the results of the computation.

Now, consider the Observable that we used earlier:

Observable.interval(0, 5, TimeUnit.SECONDS)

This Observable never completes by itself and thus it never terminates. It keeps emitting values after it has been subscribed to. Also, consider this block, found downstream down the flow:

.doOnError(error -> {
Toast.makeText(this, "We couldn't reach internet - falling back to
local data"
,
Toast.LENGTH_SHORT)
.show();
})

It maintains a strong reference to the Activity by the this reference. This means that the Activity cannot be ever reclaimed by the GC while the Observable and the Subscription are still active and, in this particular case, the Observable will never terminate by itself--it needs to be cleaned up manually.

You might ask why the Observable isn't deleted along with Activity at once because it was the Activity that created it--the thing is that Observable isn't owned by the Activity--it is basically now owned by the Thread (Scheduler) that's running it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.73.175