Reputation: 9113
I'm watching this presentation, and at 13:42 they say that using lambda in the way:
api.getEvents()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(() -> loadingIndication.show())
.doOnUnsubscribe(() -> loadingIndication.hide())
.subscribe(...);
causes View to leak.
Can you explain how the leak works in this case? Does the leak appear depending on how we compile the code and what class we put the RxJava code (e.g. in Activity, in Application, in Service)?
Upvotes: 8
Views: 2219
Reputation: 231
This causes a leak because lambdas are no different from anonymous inner classes where they will have an implicit reference to the current class where they're called, in this case it the Activity. So this piece of code actually has reference to your Activity.
api.getEvents()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(() -> loadingIndication.show())
.doOnUnsubscribe(() -> loadingIndication.hide())
.subscribe(events -> {}, throwable -> {});
I haven't had the time to checkout the video but there is a way to handle this kind of possible memory leak by using CompositeDisposable and adding the Disposable
returned from the above code through compositeDisposable.add()
and calling compositeDisposable.clear()
on your Activity's onDestroy()
.
Upvotes: 3