如果接口请求失败,使用二进制指数退避算法进行接口重试。
Observable
.create((ObservableEmitter<Object> emitter) -> {
System.out.println("开始请求接口...");
emitter.onError(new RuntimeException("请求接口异常..."));
})
.retryWhen((Observable<Throwable> errorObservable) -> errorObservable
.zipWith(Observable.just(1, 2, 4, 8, 16), (Throwable e, Integer time) -> time)
.flatMap((Integer delay) -> {
System.out.println(delay + "秒后重试");
return Observable.timer(delay, TimeUnit.SECONDS);
}))
.subscribe(System.out::println);