Rx.Observable.interval with different interval for each event

1.4k Views Asked by At

I have a bunch of events, each of which has to be triggered after the previous one with a delay specific to this event.

Rx.Observable.interval gives a possibility to provide just one interval.

Is there a way to provide different intervals?

2

There are 2 best solutions below

0
On BEST ANSWER

The solutions is a modified version of what @NiklasFasching have proposed

   Rx.Observable.from(events)
     .concatMap(function(event) { 
        return Rx.Observable.timer(event.delay);
     })
     .subscribe(...)
1
On

There is the generateWithRelativeTime operator. The official documentation is here. In short, the operator lets you specify a sequence where you can tweak when you emit each value. It is similar to a for loop except that the values are emitted asynchronously at a moment of your choice.

For example, the synchronous for loop:

for (i=1;i<4; i++) {do something}

can be turned into a sequence of values separated by 100ms, 200ms, 300ms

// Generate a value with an absolute time with an offset of 100ms multipled by value
var source = Rx.Observable.generateWithRelativeTime(
    1, // initial value
    function (x) { return x < 4; }, // stop predicate
    function (x) { return x + 1; }, // iterator
    function (x) { return x; }, // value selector
    function (x) { return 100 * x; } // time selector
).timeInterval();

By tweaking the time selector to your needs, you can have the interval between values varying.