日常问题:Rxjava的OnErrorNotImplementedException

693 阅读1分钟
Observable.create((ObservableOnSubscribe<Integer>) emitter -> {    
  doOne();
  emitter.onNext(0);
}).subscribeOn(Schedulers.io())        
.observeOn(AndroidSchedulers.mainThread())       
.subscribe(integer -> doSomeThing());

subscribe 里面是一个Consumer,只有onNext方法,没有onError方法,在Debug apk上不会报错,但是打成aar供外部调用时,会报上面的异常。

解决办法有2种:

1、把Consumer换成Observer,覆写全部方法,包括onError();

Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
    doOne();
    emitter.onNext(0);}).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<Integer>() {
            @Override            
            public void onSubscribe(Disposable disposable) { 
            }           
             @Override           
             public void onNext(Integer integer) {   
                 doSomeThing();      
            }            
            @Override           
             public void onError(Throwable throwable) {       
                 throwable.printStackTrace();           
             }            
            @Override           
             public void onComplete() {    
            }   
     });

2、Application种添加

RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
    @Override
    public void accept(Throwable e) throws Exception {
        if (e instanceof UndeliverableException) {
            e = e.getCause();
        }
        if (e instanceof IOException) {
            // fine, irrelevant network problem or API that throws on cancellation
            return;
        }
        if (e instanceof InterruptedException) {
            // fine, some blocking code was interrupted by a dispose call
            return;
        }
        if ((e instanceof NullPointerException)
                || (e instanceof IllegalArgumentException)) {
            // that's likely a bug in the application
            Objects.requireNonNull(Thread.currentThread().getUncaughtExceptionHandler())
                    .uncaughtException(Thread.currentThread(), e);
            return;
        } 
       if (e instanceof IllegalStateException) {
            // that's a bug in RxJava or in a custom operator 
           Objects.requireNonNull(Thread.currentThread().getUncaughtExceptionHandler())
                    .uncaughtException(Thread.currentThread(), e);
        } 
   }});