ame
ame

Reputation: 851

RxJS: Emit the initial value before Delay

If I use delay() function like this, it emits data only after a time delay :

const TIME_DELAY = 5000;
return new Observable(observer => {
  observer.next(res);
}).delay(TIME_DELAY);

But I need to initially emit the data, then emit it every TIME_DELAY milliseconds. How can I do this?

Upvotes: 0

Views: 1427

Answers (2)

Harijs Deksnis
Harijs Deksnis

Reputation: 1496

You should make use of timer function that allows you to specify initial delay (0 in your case), and then the interval in which the emissions repeat.

For example: const stream$ = timer(0, TIME_DELAY);

If you need to cast the result to another value or observable, you can add pipe and map or switchMap (in case of observable) operators. For example:

const stream$ = timer(0, TIME_DELAY)
 .pipe(map(() => 'some value'));

// or
const stream$ = timer(0, TIME_DELAY)
 .pipe(switchMap(() => anotherObservable$));


Upvotes: 1

mbojko
mbojko

Reputation: 14669

For your requirements, timer does exactly that. Something like:

return timer(0, TIME_DELAY).pipe(
  map(() => res)
);

https://stackblitz.com/edit/typescript-v7auxo?file=index.ts

Upvotes: 3

Related Questions