RXJava + Retrofit。每隔n秒重复一次请求

时间:2017-03-05 14:02:37

标签: android retrofit rx-java repeat

从服务器成功响应后,每n秒重复一次请求。但是查询时间中有一个字段,它会更改查询本身。 RepeatWhen - 不适合这个原因。告诉我,我该如何解决这个问题?感谢)

  AtomicBoolean onComplete = new AtomicBoolean(true);
        Observable.interval(3, TimeUnit.SECONDS)
                .compose(rxSchedulersAbs.getIOToMainTransformer())
                .map(new Func1<Long, Observable<String>>() {
                    @Override
                    public Observable<String> call(Long tick) {
                        if (onComplete.get()) {
                            onComplete.set(false);
                            return requestCreator.getSyncMessage();
                        }
                        return null;
                    }
                }).map(sync -> {
            if (sync != null)
                onComplete.set(true);
            return sync;
        }).subscribe();

1 个答案:

答案 0 :(得分:1)

如果您想根据服务器发回的内容更改请求的频率,我建议使用BehaviorSubject

BehaviorSubject<Integer> delayObs = BehaviorSubject.create(3);
delayObs
.serialize()
.flatMap(delay -> Observable.timer(delay, TimeUnit.SECONDS))
.flatMap(dummy -> requestCreator.getSyncMessage())
.onErrorResumeNext(e -> {
   if(e instanceof IOException) {
     delayObs.onNext(3);
     return Observable.empty();
   } else {
     return Observable.error(e);
   }
}
.doOnNext(sync -> {
    if(sync == null) {
      delayObs.onComplete();
    } else {
      delayObs.onNext(getNextInterval(sync));
    }
}
.compose(rxSchedulersAbs.getIOToMainTransformer())
.subscribe();

另一方面,如果您需要更改来自您收到的回复数据的请求,this might be useful