RxJava: listen for events after error

I am not fond of long and wordy articles, thus I’ll try to be concise.

Problem

As you know, the stream will be interrupted after once onError() has been called on a stream.

PublishSubject<String> publishSubject = PublishSubject.create();

publishSubject.subscribe(System.out::println, System.out::println);

publishSubject.onNext("1");
publishSubject.onError(new IllegalArgumentException("err1"));
publishSubject.onNext("2");

This will result in the following output:

1
java.lang.IllegalArgumentException: err1

Note, “2” is not present in the output, because stream is interrupted as soon as onError() is called.

Solution

PublishSubject<Notification<String>> publishSubject = PublishSubject.create();

publishSubject.subscribe(stringNotification -> {
if(stringNotification.isOnError()) {
System.out.println(stringNotification.getError());
} else {
System.out.println(stringNotification.getValue());
}
});

publishSubject.onNext(Notification.createOnNext("1"));
publishSubject.onNext(Notification.createOnError(new IllegalArgumentException("err1")));
publishSubject.onNext(Notification.createOnNext("2"));

The output is following:

1
java.lang.IllegalArgumentException: err1
2

Pay attention, there is “2” after an error event.

Thanks for reading! Bookmark, because you’ll need this one day!

Android enthusiast, Google Certified Android developer, Stackoverflower

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store