基于逻辑的 RxJava 重试 [英] RxJava retry based on logic

查看:29
本文介绍了基于逻辑的 RxJava 重试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,我有 API 调用 usign Retrofit 可能由于网络错误而失败.如果失败,我们将显示带有重试按钮的错误消息.当用户按下重试按钮时,我们需要再次重试最新的 Observable.

Here is the case, I have API call usign Retrofit that might fail due to network error. If it fails we will show error message with a retry button. When user presses the retry button we need to retry the latest Observable again.

可能的解决方案:

  1. 重试:在订阅 observable 之前应该使用重试,如果发生错误,它会立即重新订阅,这是我不想要的,只有当用户按下重试按钮时,我才需要重新订阅.

  1. Retry: Retry should be used before subscribing to the observable and it will immediately resubscribe again if error happens and that is what I don't want, I need to resubscribe only if the user pressed the Retry button.

RetryWhen:它会在您发出项目时不断尝试,直到您发出 Observable 错误,然后它才会停止.同样的问题,除非用户决定,否则我不需要开始重试过程.

RetryWhen: It Will keep trying as you emit items until you emit Observable error then it will stop. Same issue here, I need to not start the retry process unless the use decides to.

重新订阅同一个 Observable:这个解决方案将开始发出 Observable 项目,问题在于我们使用了缓存操作符,所以如果一个 Observable 失败,我们会缓存失败的项目,当我们这样做时再次订阅,我们又遇到了同样的错误.

Resubscribe to the same Observable: This solution will start emitting the Observable items, the problem with this is that we are using the cache operator, so if one Observable failed, we got the failed item cached and when we do subscribe again, we got the same error again.

还有其他解决方案吗?

推荐答案

您可以使用 retryWhen,它的参数 - Func1 - 返回一个 Observable,指示何时应该重试.例如:

You can go with retryWhen, which parameter - Func1 - returns an Observable which indicates when a retry should happen. For example :

PublishSubject<Object> retryButtonClicked = PublishSubject.create();

Observable
        .error(new RuntimeException())
        .doOnError(throwable -> System.out.println("error"))
        .retryWhen(observable -> observable.zipWith(retryButtonClicked, (o, o2) -> o))
        .subscribe();

retryButtonClicked.onNext(new Object());

每次 retryButtonClicked 发出一个事件,Observable 都会被重试

every time retryButtonClicked emmits an event, Observable will be retried

这里还有一个例子 - https://gist.github.com/benjchristensen/3363d420607f03307dd0

Here's also an example - https://gist.github.com/benjchristensen/3363d420607f03307dd0

这篇关于基于逻辑的 RxJava 重试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆