RxJS: how to emit values of a certain buffer size with a delay between each group

非 Y 不嫁゛ 提交于 2020-08-10 10:51:52

问题


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.

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

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

Also available here on stackblitz

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.

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?

Thanks in advance.


回答1:


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


来源:https://stackoverflow.com/questions/62812024/rxjs-how-to-emit-values-of-a-certain-buffer-size-with-a-delay-between-each-grou

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!