24

can someone explain me why code like this:

 networApi.getList()
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnError(throwable -> {
                throwable.getMessage();
            })
            .doOnNext(list -> {
                coursesView.populateRecyclerView(list);
                courseList = (List<Course>) courses;
            }).subscribe();

If there is no internet goes into doOnError but throws it further so the app goes down, but code like this:

networkApi.getList()
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<List<? extends Course>>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    e.getMessage();
                }

                @Override
                public void onNext(List<? extends Course> list) {
                    coursesView.populateRecyclerView(list);
                    courseList = (List<Course>) list;
                }
            });

Work how I expect, it means when there is no internet connection it does nothing.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
wojciech_maciejewski
  • 1,277
  • 1
  • 12
  • 28

1 Answers1

43

Basically, doOnError does not handle the error, in the sense that it does not consume it. It just does something with it, log it, for example. (The same is true for doOnNext - it also does not consume the item and the item still ends up in onNext of the Subscriber).

The error is still sent down the chain and would still end up in the onError of your Subscriber.

I am pretty certain that your app is crashing with an OnErrorNotImplementedException and that is because you don't have any Subscriber at all and therefore no onError method.

david.mihola
  • 12,062
  • 8
  • 49
  • 73
  • @david.mihola is there a way to handle HTTP status codes onError with retrofit beta 2 ? – halfred Nov 12 '15 at 15:18
  • 1
    Yeah it works, but why? it is not clear for me why doOnError doesn't work. can you give an example of a good usage of doOnError? – Jhon Fredy Trujillo Ortega Feb 14 '18 at 22:54
  • 2
    @JhonFredyTrujilloOrtega: Other than logging, not really. It's tempting to use it for UI updates (hide progress indicator when a network request emits `onError`), but see Jake Wharton's talk http://jakewharton.com/the-state-of-managing-state-with-rxjava/ for a cleaner alternative that doesn't use `doOn*` methods. – david.mihola Feb 20 '18 at 07:19