Search code examples
androidrx-javarx-java2

RxJava doOnError vs onError


I am try to use the following code

initLocalSettingsIfNeed()
                            .andThen(initGlobalSettingsIfNeed(configuration))
                            .doOnComplete(callback::onSuccess)
                            .doOnError(throwable -> callback.onError(throwable.getLocalizedMessage()))
                            .subscribe();

But I have exception

The exception was not handled due to missing onError handler in the subscribe() method call.

I guess I am not using this methods correctly, I thought can replace doOnComplete doOnError with observer inside subscribe() method, I am wrong?


Solution

  • Regarding your original question, you have to know that doOnError is not a replacement of onError:

    Actually there’s one key difference between them. doOnError() basically only triggers its callback, then passes down the encountered errors to the down stream. So if the whole stream is subscribed without the onError callback in subscribe(), your app will crash by OnErrorNotImplementedException.

    The onError callback in subscribe() in the other hand does consume the errors. That means, it will catch the errors, and let you handle them without re-throwing the errors by itself.

    About the warning you mention in one comment:

    This approach is working, but i have warning 'the result of subscribe not used', as i know this need to be disposed automatically when onError or onComplete is called, is there way to avoid this warning? – Pavel Poley

    A good approach is that your methods inside your Repository return a Observable, and then you can subscribe to them in your ViewModel. Then, in every ViewModel class you can have a member variable with a CompositeDisposable where you can add the disposable of each subscription to the Observables returned by your repository. Finally, you should override the onCleared method to dispose all the disposables stored in the CompositeDisposable.

    public class MyViewModel extends ViewModel {
    
        private MyRepository myRepository;
        private final CompositeDisposable disposables;
    
        @Inject
        public MyViewModel(MyRepository myRepository) {
            ...
            this.myRepository = myRepository;
            disposables = new CompositeDisposable();
            ...
        }
    
        public void callObservableInRepository() {
             disposables.add(myRepository.myObservable()
                                  .subscribe(onSuccess -> {...} , onError -> {...}));
        }
    
        @Override
        protected void onCleared() {
            disposables.clear();
        }
    
    }