Observable and how to control results pace

2019-07-14 14:24发布

问题:

I am looking for an operator that would help me pace the results emitted from an observable, it would look like this :

[--A-BC--D-E----------------]
[--A----B----C----D----E----]

I tried AuditTime() but it does not replay the results that was emitted between intervals, it does something like this :

[--A-BC--D-E----------------]
[--A----C----E--------------]

Thanks for your help.

回答1:

I think this should do what you need:

const e1 =  cold('--A-BC--D-E----------------|');
const expected = '--A----B----C----D----E----|';

const source = e1.pipe(
  concatMap(val => of(false).pipe(
    delay(5, scheduler),
    takeWhile(Boolean),
    startWith(val),
  )),
);

expectObservable(source).toBe(expected);

The trick here is that I'm using concatMap to always wait until the previous Observable completes. The inner Observable emits the value and then postpones its own completion and thus concatMap enforces the delay between two emissions.

See live demo: https://stackblitz.com/edit/rxjs6-test-scheduler?file=index.ts