如何在rxjava中重试时使用RetryAfter Header

时间:2018-01-23 20:13:36

标签: android rx-java

出现异常时,我有以下重试代码

.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() 
{
                    @Override
                    public Observable<?> call(Observable<? extends Throwable> observable) {
                        return observable.zipWith(retryRange, new Func2<Throwable, Integer, Object>() {
                            @Override
                            public Object call(@Track Throwable throwable, Integer retryCount) {
                                return retryCount;
                            }
                        });
                    }
            })

如果在retryRange之前有异常,此代码将继续重试api调用。

我需要在这里添加一个检查来获取errorCode,如果是503,那么我需要检查标题值&#34; retryAfter&#34;并利用这段时间来延迟重试。 我不知道如何在上面的重试中获取标题,并使用它延迟重试

1 个答案:

答案 0 :(得分:0)

以下解决方案对我有用:

  .retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
                    @Override
                    public Observable<?> call(Observable<? extends Throwable> observable) {
                        return observable.zipWith(retryRange, new Func2<Throwable, Integer, Object>() {
                            @Override
                            public Object call(@Track Throwable throwable, Integer attempt) {

                                return throwable;
                            }
                        }).flatMap((new Func1<Throwable, Observable<?>>() {
                            @Override
                            public Observable<?> call(Throwable throwable) {
                                long delayTime = 0;
                                if (throwable instanceof HttpException && ((HttpException) throwable).code() == 503) {
                                    HttpException exception = (HttpException) throwable;
                                    Response response = exception.getErrorResponse();
                                    delayTime = getDelayTime(response.headers());

                                }
                                return Observable.timer(delayTime, TimeUnit.MILLISECONDS);
                            }
                        }));