RxJS - How to incrementally increase the delay time without using interval?
Asked Answered
M

2

1

I want to incrementally increase the delay for this:

const source = from(839283, 1123123, 63527, 4412454); // note: this is random
const spread = source.pipe(concatMap(value => of(value).pipe(delay(1000)))); // how to incrementally increase the delay where the first item emits in a second, the second item emits in three seconds, the third item emits in five seconds, and the last item emits in seven seconds.
spread.subscribe(value => console.log(value));

I'm aware of using interval to incrementally increase the delay time as below. But I also need to consume this source const source = from(839283, 1123123, 63527, 4412454);

const source = interval(1000); // But I also need to use have this from(839283, 1123123, 63527, 4412454)
const spread = source.pipe(concatMap(value => of(value).pipe(delay(value * 200))));
spread.subscribe(value => console.log(value

How to incrementally increase the delay time when starting with const source = from(839283, 1123123, 63527, 4412454); ?

Mayman answered 31/10, 2020 at 19:18 Comment(0)
D
3

You can use the index of the emitted value and calculate the delay based on that.

concatMap((value, index) => {
  return of(value).pipe(delay((index > 2 ? 7 : index) * 1000));
})

Here is a stackblitz for a complete example with your snippet: https://stackblitz.com/edit/rxjs-jjmlta?devtoolsheight=60

Derman answered 31/10, 2020 at 21:47 Comment(0)
E
0

The second parameter of concatMap is an index which can be multiplied by 1000 to give the sequence 0, 1000, 2000... The sequence 1000, 3000, 5000... can then be created with 1000 * (i * 2 + 1):

const {concatMap, delay, from, of} = rxjs;

from([839283, 1123123, 63527, 4412454])
  .pipe(concatMap((value, i) =>
    of(value).pipe(delay(1000 * (i * 2 + 1)))
  ))
  .subscribe(value => console.log(value));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.5.6/rxjs.umd.min.js"></script>
Exsert answered 31/10, 2020 at 19:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.