I have a lot of Single
's in my code, such as
Disposable disp = Single.fromCallable(()-> loadData())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(res-> showInUI(res),
throwable -> Log.e(TAG, throwable.getMessage()))
);
As I understood from the documentation, the difference between Observable
and Single
is that Single can respond with an error, Never respond, Respond with a success and it emits only once.
Now I do not dispose anywhere and everything works fine.
So do I need to execute disp.dispose()
at all?
Yes, indeed, it doesn't matter whether it is Single
/Observable
/Completable
.
It is matter as you don't want to keep your UI bound to a some background work, that will leak your Activity.
It's also matter cause you don't want to get notification at the UI beyond some point (after your Activity
destroyed for instance) that can cause NPEs or other problems.
Besides that, it's a good practive to cancel and stop expensive background work when user leave/close the Activity
/Screen
is in, in order to clear resources.
All of those considerations are common to all Observable
types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With