Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If my RxJava 2 call returns a Single or Maybe, do I still need to use CompositeDisposable?

Suppose I have

Disposable disposable = signOutUser()
            .subscribe((Response<ResponseBody> response) -> {
                if (response.isSuccessful()) {
                    Intent intent = new Intent(view.getContext(), SignInUserActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
                    view.getContext().startActivity(intent);
                    ((FragmentActivity) view.getContext()).finish();
                }
            }, (Throwable ex) -> {
                Log.e(TAG, "signOutUser: " + ex.getMessage());
            });

where signOutUser() returns Single<Response<ResponseBody>>. When signOutUser() is successful, there is an Intent and the current activity is finished(). Otherwise, it fails, possibly due to network error, so there is no intent and the user stays on current activity.

Since this isn't something to observe (it's a one time event, success or fail), and IF the user successfully logs out, then onDestroy will be called which calls compositeDisposable.clear() which clears all the disposables. So then I'm adding a Disposable and immediately that Disposable is being disposed or cleared.

My question is, do I event need to use Composite Disposable? Do I immediately call disposable.dispose() after subscribe? Do I set anything to null? Do I not use Single?

like image 839
bycfly Avatar asked Jan 26 '18 23:01

bycfly


1 Answers

Do I event need to use Composite Disposable?

Yes, you should always use composite disposable (or normal Disposable), and unsubscribe from it when the time comes (onDestroy/onStop whathere you need). The reason for it is that the network call may be finished after you have closed activity, which will result in memory leaks or even crashes (because context will be null).

Do I immediately call disposable.dispose() after subscribe?

No, because this would result in the call to never return a result. If you dispose immediately after calling subscribe, you will never get a response from it. Read about what happens after you dispose an observable.

Do I set anything to null?

No need to. If your single has finished, you don't have to do anything about it. And there won't be any problems that it is still in CompositeDisposable (even if you call dispose on it). Actually, after the Single is finished, RxJava will dispose the observable itself to safe some memory.

Do I not use Single?

Yes, this is perfect situation to use it. You want to perform a single request, no need to use Observable.

like image 55
Kamil Dziadek Avatar answered Oct 02 '22 23:10

Kamil Dziadek