【问题标题】:How to emit values of a certain buffer size with a delay between each group如何在每组之间延迟发出特定缓冲区大小的值
【发布时间】:2020-07-09 09:42:50
【问题描述】:

我有大量的可观察值,我想将其分块成固定大小,然后延迟发出每个块直到完成。

更具体地说,我的场景是我可能有大量数据要通过 http 请求发送到服务器,其中每个值都需要单独的 http 请求。因此,如果我有 1000 个待处理的数据位,我不想一次做 1000 个 http 请求,我可能想说做 10 个,然后延迟一小段时间(可能是几秒钟)。

我认为这必须使用bufferoperator,但不能完全让它做我想做的事。我浏览了许多示例,但没有找到一个可以做到这一点的示例。

这里是一个简单的例子,我一直在尝试(但不正确)...

    import { interval,of , range} from 'rxjs';
    import { buffer, bufferTime, delay, throttleTime, bufferCount, take } from 'rxjs/operators';

    const source = range(1,1000);
    const example = source.pipe(bufferCount(10), delay(5000));
    const subscribe = example.subscribe(val =>
        console.log('output:', val)
    );

也可以使用here on StackBlitz

查看输出,我们可以看到是否将它们分成 10 个块,但它只是等待 5000 毫秒并将它们全部输出。

我希望前 10 个立即发出,然后每个后续都延迟,在这种情况下,延迟 5 秒。我该怎么做?

【问题讨论】:

标签: javascript rxjs


【解决方案1】:

您可能想尝试以下方法:

 const source = range(1, 1000);

 const example = source
   .pipe(
     bufferCount(10),
     concatMap(x => of(x).pipe(delay(5000))),
    );
   
 const subscribe = example.subscribe(val =>
   console.log('output:', val)
 );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多