问题
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 buffer
operator, 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