admin管理员组

文章数量:1399278

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

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

Share Improve this question asked Dec 10, 2017 at 9:23 Royi NamirRoyi Namir 149k144 gold badges492 silver badges831 bronze badges 2
  • reactivex.io/documentation/operators/delay.html – user184994 Commented Dec 10, 2017 at 9:49
  • @user184994 that's not the same as what I wanted. I want to emit 1....delay...2 .....delay.....3. Not ....delay......1,2,3 – Royi Namir Commented Dec 10, 2017 at 9:49
Add a ment  | 

1 Answer 1

Reset to default 7

You can delay each emission itself and wait until the previous one pleted. 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 plete (for example with take() or takeUntil()).

本文标签: javascriptHow can I emit values with delay in RXJSStack Overflow