kharandziuk
kharandziuk

Reputation: 12890

Rx randomInterval

I need a way to create randomInterval stream(similar to interval).

It should produce stream like this:

V-V-----V--V-V-VVV-V

When interval creates a stream like:

V--V--V--V--V--V--V--V

How can I achieve such behavior?

Upvotes: 2

Views: 103

Answers (2)

user3743222
user3743222

Reputation: 18665

That question was already asked here. Cf RXJS: How can I generate a stream of numbers at random intervals (within a specified range)?

You should be able to make up an answer to your problem from that only if you have a finite number of random intervals that you want to generate though.

var source = Rx.Observable
  .range(1, 10)
  .concatMap(function (x) {
    return Rx.Observable
      .of(x)
      .delay(randomDelay(1000,5000));
  })
 .timeInterval();

For a version with infinite generation of random intervals:

function sum(a,b) {return a+b}

var source = Rx.Observable.of(1)
 .flatMap(x => Rx.Observable.of(x).delay(randomDelay(bottom,top))
 .repeat()
 .scan(sum, initialNumber)

 function randomDelay(bottom, top) {
  return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}

 source.subscribe(function(x){console.log(x)})

PS : if you are using Rxjs v4 or lower, the answer proposed by the OP is in my opinion the best answer as it uses a operator specialized to this purpose. If you are using RxJS v5, currently in beta, I could not find the operator generateWithRelativeTime in the distribution, so you can resort to the answer mentioned here.

Upvotes: 1

kharandziuk
kharandziuk

Reputation: 12890

I finished with solution below:

    rx.Observable.generateWithRelativeTime(
        1,
        function (x) { return true; },
        function (x) { return x + 1; },
        function (x) { return x; },
        function (x) { return math.randomInt(100,500); }
    ).timeInterval()
    .do(console.log).subscribe();

Upvotes: 2

Related Questions