java出现错误 2,如何在RxJava 2中发生错误后继续处理?

I have a PublishSubject and a Subscriber which I use to process a (possibly) infinite stream of preprocessed data. The problem is that some of the elements might contain some error. I'd like to ignore them and continue processing. How can I do so? I've tried something like this:

val subject = PublishSubject.create()

subject.retry().subscribe({

println("next: $it")

}, {

println("error")

}, {

println("complete")

})

subject.onNext("foo")

subject.onNext("bar")

subject.onError(RuntimeException())

subject.onNext("wom")

subject.onComplete()

My problem is that none of the error handling methods help me out here:

onErrorResumeNext() — instructs an Observable to emit a sequence of

items if it encounters an error

onErrorReturn( ) — instructs an

Observable to emit a particular item when it encounters an error

onExceptionResumeNext( ) — instructs an Observable to continue

emitting items after it encounters an exception (but not another

variety of throwable)

retry( ) — if a source Observable emits an

error, resubscribe to it in the hopes that it will complete without

error

retryWhen( ) — if a source Observable emits an error, pass that

error to another Observable to determine whether to resubscribe to the

source

I tried retry() for example but it hangs my process after the error indefinitely.

I also tried onErrorResumeNext() but it does not work as expected:

val backupSubject = PublishSubject.create()

val subject = PublishSubject.create()

var currentSubject = subject

subject.onErrorResumeNext(backupSubject).subscribe({

println("next: $it")

}, {

println("error")

currentSubject = backupSubject

}, {

println("complete")

})

backupSubject.subscribe({

println("backup")

}, {

println("backup error")

})

currentSubject.onNext("foo")

currentSubject.onNext("bar")

currentSubject.onError(RuntimeException())

currentSubject.onNext("wom")

currentSubject.onComplete()

This only prints foo and bar.

解决方案

If you want to continue processing after an error, it means your error is a value just like your Strings and should go through onNext. To ensure type safety in this case, you should use some form of wrapper that can either take a regular value or an error; for example, the io.reactivex.Notification is available in RxJava 2:

PublishSubject> subject = PublishSubject.create();

subject.subscribe(System.out::println);

subject.onNext(Notification.createOnNext("Hello"));

subject.onNext(Notification.createOnError(new RuntimeException("oops")));

subject.onNext(Notification.createOnNext("World"));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值