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();
}
}
onErrorComplete
, if you want to swallow the error – TahitidoOnError
in not a replacement foronError
– Tahiti