Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rx.exceptions.OnErrorNotImplementedException How do I avoid this error - its crashing my app

Tags:

rx-java

com.myapp.test.debug E/MessageQueue-JNI: rx.exceptions.OnErrorNotImplementedException at rx.Observable$31.onError(Observable.java:7134) at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:154) at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:111) at rx.observers.SafeSubscriber.onNext(SafeSubscriber.java:137) at rx.subjects.SubjectSubscriptionManager$SubjectObserver.onNext(SubjectSubscriptionManager.java:224) at rx.subjects.PublishSubject.onNext(PublishSubject.java:121) at com.myapp.MyClass.lambda$static$53(MyClass.java:77) where MyClass.java 77 MySubject.onNext(event);

A few question ... Why is the actual error not also shown in addition to error handler not implemented? Secondly where am I suppose to implement this function on my subject? How exactly would I add an Error handler to the subject. Thanks this is crashing my app and the actual error is not even shown. I guess I should always implement the error handler?

like image 297
FunctionallyReactive Avatar asked Apr 19 '16 08:04

FunctionallyReactive


1 Answers

RxJava has an Observable and an Observer. You can view the Observable as the source of your stream on which you can perform operations such as map and filter. The Observer is kind of a receiver: it is an interface with three methods (onNext, onError and onCompleted) that get triggered by the Observable. You connect an Observable and Observer via the Observable.subscribe(...) methods.

There are multiple overloads of subscribe that allow you to provide the onNext, onError and onCompleted as separate functions. These functions are then used to implement the Observer interface. If you don't provide all three functions (say only onNext), the onError method of the Observer interface is implemented by throwing an OnErrorNotImplementedException.

Presumably your code 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 the subscribe, but also providing an onError implementation:

PublishSubject<Integer> subject = PublishSubject.create();
subject.subscribe(System.out::println, Throwable::printStacktrace);
subject.onNext(1/0);

Regarding your last question "Am I supposed to always implement the onError function?": Technically speaking no, you don't need to if you are sure that the Observable (or Subject) will not produce an error. In practice however it is a smart idea to at least log this kind of error or even recover from it using an operator like onErrorResumeNext or retry. You can find all about them in the documentation.

like image 116
RvanHeest Avatar answered Sep 24 '22 02:09

RvanHeest