Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RXJava2. Do I need dispose streams which emits once? (Single, Maybe)

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?

like image 936
Rainmaker Avatar asked May 22 '17 10:05

Rainmaker


1 Answers

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.

like image 97
yosriz Avatar answered Dec 01 '22 11:12

yosriz