RxJS:如何在每组之间延迟发出特定缓冲区大小的值 [英] RxJS: how to emit values of a certain buffer size with a delay between each group

查看:27
本文介绍了RxJS:如何在每组之间延迟发出特定缓冲区大小的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have large observable of values, where I want to chunk it into fixed sizes, and then emit each chunk with a delay until finished.

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

To be a bit more concrete, my scenario is where I may have a lot of data to send to a server via a http request, where each values needs a separate http request. So if I have 1000 pending bits of data, I don't want to do 1000 http request all at once, I may like to say do 10, and then delay by a short time (maybe a couple of seconds).

我认为这必须使用 buffer 运算符,但不能完全让它做我想做的事.我查看了许多示例,但没有找到一个可以做到这一点.

I assume this must use the bufferoperator, but can't quite get it to do what I want. I have looked through many example, but ont found one that does exactly this.

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

Here is a simple example, I have been trying (but not correct)...

    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)
    );

也可以在这里在stackblitz

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

Looking at the output, we can see if divides them into chunks of 10, but it then just waits 5000 ms and outputs them all.

我希望立即发出前 10 个,然后每个后续都延迟,在这种情况下,延迟 5 秒.

I would like the first 10 to be emitted straight away, and then each subsequent to be delayed, in this case, by the 5 seconds.

有人对如何做到这一点有任何指示吗?

Anyone have any pointers on how to do this?

提前致谢.

推荐答案

您可能想尝试以下操作:

You might want to try the following:

 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)
 );

这篇关于RxJS:如何在每组之间延迟发出特定缓冲区大小的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆