Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I emit values with delay in RXJS?

I have an array of values [1,2,3] .

I want to emit each value with delay

I've managed to do it with the zip operator :

 Rx.Observable.from([1,2,3])
   .zip(Rx.Observable.timer(0, 1000), x => x)
   .subscribe((e) => console.log(e));

Question:

Is there any more appropriate operator for such task ? Involving an inner observable seems ( to me) incorrect approach.
Should I unsubscribe the inner Observable manually ? Becuase basically no one tells it to stop.

jsbin

like image 965
Royi Namir Avatar asked Mar 08 '23 09:03

Royi Namir


1 Answers

You can delay each emission itself and wait until the previous one completed. Like this for example:

Rx.Observable.from([1,2,3])
   .concatMap(x => Observable.of(x).delay(1000)) // or Observable.timer(1000).mapTo(x)
   .subscribe((e) => console.log(e));

If you want to use zip you don't need to unsubscribe the timer but you need to tell it to complete (for example with take() or takeUntil()).

like image 62
martin Avatar answered Apr 27 '23 00:04

martin