RxJava有条件地延迟响应

时间:2018-04-04 07:12:33

标签: rx-java2 rx-android

我想将响应延迟最多500毫秒。 如果updateData已经花了400毫秒,那么我想延迟100毫秒。

以下代码总是延迟500毫秒。 目前如果后端需要600毫秒,则总延迟为1100毫秒,但如果超过500毫秒,我不想延迟。

compositeDisposable.add(someRepo.updateData(dataRequest)
.observeOn(schedulerProvider.mainThread())
.delay(500, TimeUnit.MILLISECONDS)
.subscribeWith(dataUpdateObserver())

2 个答案:

答案 0 :(得分:1)

试试这样。当你开始someRepo.updateData(dataRequest)时,启动计时器parellally。然后在完成someRepo.updateData(dataRequest)时获取计时器计数并找到所需的延迟。

如果它已超过500毫秒,则不再需要延迟。否则找到所需的延迟(500 - elapsedTime)。以下代码也是如此。此处someRepo.updateData(dataRequest)返回Single<DataResponse>

   Subject<Boolean> timerStopper = PublishSubject.create(); // To terminate the timer
   Observable<Long> timer = Observable.interval(1, TimeUnit.MILLISECONDS)
                .takeUntil(timerStopper).publish().refCount();


   someRepo.updateData(dataRequest).doOnSubscribe(__ -> timer.subscribe())
  .flatMap(dataResponse -> timer.flatMapSingle(elapsed -> {
         timerStopper.onNext(true); // take the elapsed time and terminate the timer
         long requiredDelay = elapsed > MAX_DELAY ? 0 : MAX_DELAY - elapsed; // find the required delay from elapsed. If its already exceeded Maximum delay, no delay is required
         Log.d(TAG, "requiredDelay: " + requiredDelay);
         return Single.fromCallable(() -> dataResponse).delay(requiredDelay, TimeUnit.MILLISECONDS);})
        .map(data -> data).firstOrError())
   .subscribeWith(dataUpdateObserver());

答案 1 :(得分:0)

您可以定义一个全局变量来获取updateData操作的总时间,并根据花费的时间,使用延迟值

long total = 0;

@Test
public void customDelay() {
    long start = System.currentTimeMillis();
    Subscription subscription = Observable.just("hello reactive world with custom delay")
            .map(value -> {
                //updateData logic
                try {
                    Thread.sleep(new Random().nextInt(600));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                total = System.currentTimeMillis() - start;
                if (total > 500) total = 0;
                return value;
            })
            .delay(total, TimeUnit.MILLISECONDS)
            .subscribe(n -> System.out.println("time:" + (System.currentTimeMillis() - start)));
    new TestSubscriber((Observer) subscription).awaitTerminalEvent(1000, TimeUnit.MILLISECONDS);
}

您可以看到此处运行的示例https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/utils/ObservableDelay.java