RxJava操作符-异常处理系

一般情况下,RxJava产生的一切异常,都会传递至onError进行处理。但在有些情况下,我们需要在onError之前捕获这些异常并作相应的处理,此时就用到了RxJava的Error Handling系列操作符。

RxJava的Error Handing系列操作符有3个:

  • onErrorReturn
  • onErrorResumeNext
  • onExceptionResumeNext

onErrorReturn(Func1)


The onErrorReturn method returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes onError in which case, rather than propagating that error to the observer, onErrorReturn will instead emit a specified item and invoke the observer’s onCompleted method.

以上为doc说明,说白了就是该操作符会拦截(拦截指的是不会触发onError,下同)发送给观察者的异常,并发送出一个正常的item,这个item需要我们自己在Func1中自定义。

.onErrorReturn(new Func1<Throwable, Object>() { 
    @Override 
    public Object call(Throwable throwable) { 
        // TODO: handle throwable then return specified object 
        return null; 
    }
})

onErrorResumeNext(Func1)

onErrorResumeNext(Observable)


The onErrorResumeNext method returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes onError in which case, rather than propagating that error to the observer, onErrorResumeNext will instead begin mirroring a second, backup Observable.

同样是产生源Observable的镜像,拦截异常,并向事件流发射一个Observable,可直接传入一个Observable对象,或由Func1生成。

onExceptionResumeNext(Observable)


Much like onErrorResumeNext method, this returns an Observable that mirrors the behavior of the source Observable, unless that Observable invokes onError in which case, if the Throwable passed to onError is an Exception, rather than propagating that Exception to the observer, onExceptionResumeNext will instead begin mirroring a second, backup Observable. If the Throwable is not an Exception, the Observable returned by onExceptionResumeNext will propagate it to its observer’s onError method and will not invoke its backup Observable.

和onErrorResumeNext很像,只不过此操作符拦截的是Exception,并且参数只能是Observable对象。需注意的是,如果产生的Throwable不是Exception,会被发送至由onExceptionResumeNext返回的Observable所注册的Observer中,而不会调用backup Observable(这个backup是指的什么,源Obervable吗?)。

doOnError(Action1)


这个操作符并不在官方文档的Error Handling系列中,而属于Do系列,和Error Handling系列不同,doOnError并不会拦截异常,只是通过Action1回掉传入Thorwable,该Throwable还是会发送至onError。

之所以放在这里一起说,是因为我在开发时需要在返回未登陆异常的时候,清除一下本地的UserCache,异常还是需要被正常发送给观察者。最开始还用onErrorReturn去处理,完成后再手动抛出一个RuntimeException,结果导致产生其他Exception或Throwable时不能得到正确处理,真是傻透了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 注:只包含标准包中的操作符,用于个人学习及备忘参考博客:http://blog.csdn.net/maplejaw...
    小白要超神阅读 4,545评论 0 3
  • 作者: maplejaw本篇只解析标准包中的操作符。对于扩展包,由于使用率较低,如有需求,请读者自行查阅文档。 创...
    maplejaw_阅读 46,077评论 8 93
  • 本篇文章介主要绍RxJava中操作符是以函数作为基本单位,与响应式编程作为结合使用的,对什么是操作、操作符都有哪些...
    嘎啦果安卓兽阅读 7,926评论 0 10
  • 我从去年开始使用 RxJava ,到现在一年多了。今年加入了 Flipboard 后,看到 Flipboard 的...
    Jason_andy阅读 10,931评论 7 62
  • 【0512今日话题】 你经历过的最难忘的生日是哪一次?(不管是别人的还是自己的。) 看到这个问题的时候,首先浮现在...
    冰棍儿嗝阅读 2,828评论 7 2

友情链接更多精彩内容