RxJava retryWhen操作符实现错误重试机制
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了RxJava retryWhen操作符实现错误重试机制,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2756字,纯文字阅读大概需要4分钟。
内容图文
业务需求
当我们在app里发起网络请求时,可能会因为各种问题导致失败。如何利用RxJava来实现出现错误后重试若干次,并且可以设定重试的时间间隔。
具体实现
网络请求使用Retrofit来做,请求用户信息接口
@GET("/userinfo?noToken=1")
Observable<Response> getUserInfoNoToken();
请求用户信息接口的逻辑代码
userApi.getUserInfoNoToken()
//总共重试3次,重试间隔3000毫秒
.retryWhen(new RetryWithDelay(3, 3000))
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Action1<Response>() {
@Overridepublicvoidcall(Response response) {
String content = new String(((TypedByteArray) response.getBody()).getBytes());
printLog(tvLogs, "", content);
}
}, new Action1<Throwable>() {
@Overridepublicvoidcall(Throwable throwable) {
throwable.printStackTrace();
}
});
RetryWithDelay代码:
public
class
RetryWithDelay
implements
Func1<Observable<? extendsThrowable>, Observable<?>
> {
private final int maxRetries;
private final int retryDelayMillis;
private int retryCount;
public RetryWithDelay(int maxRetries, int retryDelayMillis) {
this.maxRetries = maxRetries;
this.retryDelayMillis = retryDelayMillis;
}
@Override
public Observable<?> call(Observable<? extendsThrowable> attempts) {return attempts
.flatMap(new Func1<Throwable, Observable<?>>() {
@Override
public Observable<?> call(Throwable throwable) {
if (++retryCount <= maxRetries) {
// When this Observable calls onNext, the original Observable will be retried (i.e. re-subscribed).
printLog(tvLogs, "", "get error, it will try after " + retryDelayMillis
+ " millisecond, retry count " + retryCount);
return Observable.timer(retryDelayMillis,
TimeUnit.MILLISECONDS);
}
// Max retries hit. Just pass the error along.return Observable.error(throwable);
}
});
}
}
如何模拟重试呢?
方法一:把服务器关闭,关闭服务器后,客户端请求接口的必然会报错,看看是不是重试三次。
运行输出:
‘geterror, it will tryafter3000 millisecond, retry count1‘
Main Thread:false, Thread Name:Retrofit-Idle
‘geterror, it will tryafter3000 millisecond, retry count2‘
Main Thread:false, Thread Name:Retrofit-Idle
‘geterror, it will tryafter3000 millisecond, retry count3‘
Main Thread:false, Thread Name:Retrofit-Idle
上面是重试三次了,但是我们怎么知道,如果在服务器启动后,在接下的重试中请求成功呢?接下来试试方法二。
方法二:先把服务器关闭,当点击按钮请求的同时,启动Tomcat服务器。
运行输出:
‘geterror, it will tryafter3000 millisecond, retry count1‘
Main Thread:false, Thread Name:Retrofit-Idle
‘geterror, it will tryafter3000 millisecond, retry count2‘
Main Thread:false, Thread Name:Retrofit-Idle
‘username:chiclaim,age:007‘
Main Thread:true, Thread Name:main
可以发现,在第三次重试的时候,服务器可用了。
转自:http://blog.csdn.net/johnny901114/article/details/51539708
原文:http://blog.csdn.net/jdsjlzx/article/details/51722365
内容总结
以上是互联网集市为您收集整理的RxJava retryWhen操作符实现错误重试机制全部内容,希望文章能够帮你解决RxJava retryWhen操作符实现错误重试机制所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。