RxJava has Observable and Observer . You can view Observable as the source of your stream, on which you can perform operations such as map and filter . Observer is a kind of receiver : it is an interface with three methods ( onNext , onError and onCompleted ) that are launched using the Observable . You connect Observable and Observer using the methods Observable.subscribe(...) .
There are several subscribe overloads that allow you to provide onNext , onError and onCompleted as separate functions. These functions are then used to implement the Observer interface. If you do not provide all three functions (say, only onNext ), the onError method of the Observer interface is implemented by throwing an OnErrorNotImplementedException .
Your code supposedly looks something like this.
PublishSubject<Integer> subject = PublishSubject.create(); subject.subscribe(System.out::println); // I use a Java 8 lambda here for brevity subject.onNext(1/0); // this causes an error for dividing by 0
You can catch this exception by not only providing an onNext implementation in subscribe , but also by providing an onError implementation:
PublishSubject<Integer> subject = PublishSubject.create(); subject.subscribe(System.out::println, Throwable::printStacktrace); subject.onNext(1/0);
Regarding your last question, “Should I always execute the onError function?”: Technically speaking no, you do not need it if you are sure that the Observable (or Subject ) will not produce an error. In practice, however, it is a reasonable idea to at least register such an error or even repair it using an operator like onErrorResumeNext or retry . You can find everything about them in the documentation .
source share