简体   繁体   English

使用RxJS运算符延迟HTTP请求

[英]Delay HTTP-Requests with RxJS operators

I have an Observable myObservable which gets some items emitted with different time intervals. 我有一个Observable myObservable ,它以不同的时间间隔发出一些项目。 For example the time interval between the first and the second item could be 1 second and for the second and third item this could be 3 seconds. 例如,第一项和第二项之间的时间间隔可以是1秒,而第二项和第三项之间的时间间隔可以是3秒。 For each item a HTTP request is send with the method this.sendMessage() . 对于每个项目,都会使用this.sendMessage()方法发送HTTP请求。

The problem is that the time interval between the request should be at least two second. 问题在于请求之间的时间间隔应至少为两秒。 Delay all request for two seconds is not the best solution. 将所有请求延迟两秒钟不是最佳解决方案。 For example for the first request I don't want a delay. 例如对于第一个请求,我不想延迟。 I don't want a delay too when the time difference between two emitted items is more than two seconds. 当两个发射项目之间的时间差超过两秒时,我也不想延迟。

This is a working solution which does what I want. 这是我想要的工作解决方案。 But I wonder if there is a more rxjs-like solution? 但是我想知道是否还有类似rxjs的解决方案? I play with delay() and delayWhen() but I didn't find a way to get this working. 我使用delay()delayWhen()玩,但是我没有找到一种方法来delayWhen()工作。 Does anyone has a solution? 有没有人有解决方案?

let lastSendTimestamp = null;

myObservable.pipe(
  concatMap(async body => {

    // Calculate delay time
    let delayTime = 0;
    if (!lastSendTimestamp) {
      delayTime = 0;
    } else if (Date.now() - lastSendTimestamp > 2000) {
      delayTime = 0;
    } else {
      delayTime = 2000 - (Date.now() - lastSendTimestamp);
    }

    // Wait until delay is over
    await new Promise(resolve => setTimeout(resolve, delayTime));

    lastSendTimestamp = Date.now();

    return await this.sendMessage(body);
  }),
).subscribe(result => {
});

You can use timer instead and chain with the async request. 您可以改用timer并与异步请求链接。 There's no need for promise 不需要承诺

let lastSendTimestamp = null;

myObservable.pipe(
  concatMap(body => {

    // Calculate delay time
    let delayTime = 0;
    if (!lastSendTimestamp) {
      delayTime = 0;
    } else if (Date.now() - lastSendTimestamp > 2000) {
      delayTime = 0;
    } else {
      delayTime = 2000 - (Date.now() - lastSendTimestamp);
    }
    lastSendTimestamp = Date.now();
    return timer(delayTime).pipe(concatMap(res=>this.sendMessage(body)));
  }),
).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM