John Abraham
John Abraham

Reputation: 18821

Generate a stream of values over random intervals in rxjs6?

How can I set the value of randomIntervals for each iteration of interval?

import {random} from 'lodash'
import {interval, timer} from 'rxjs';
import {takeUntil} from 'rxjs/operators';

const timer$ = timer(5000);
const randomInterval = random(100, 1000);
const source = interval(randomInterval)
  .pipe(
    takeUntil(timer$)
  );
source.subscribe(console.log)

Upvotes: 0

Views: 369

Answers (2)

Adrian Brand
Adrian Brand

Reputation: 21658

What about this? An interval of zero that returns items with a random delay.

const { interval, of } = rxjs;
const { concatMap, delay } = rxjs.operators;

interval(0).pipe(
  concatMap(i => of(i).pipe(delay(Math.random() * 5000)))
).subscribe(val => { console.log(val); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>

Upvotes: 1

Adrian Brand
Adrian Brand

Reputation: 21658

I don't think you can specify a random interval but you could use a timeout

const { BehaviorSubject } = rxjs;

const random$ = new BehaviorSubject(1);

random$.subscribe(val => { console.log(val); });

random();

function random() {
  random$.next(random$.getValue() + 1);
  setTimeout(random, Math.random() * 5000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>

Or there is this answer

RXJS: How can I generate a stream of numbers at random intervals (within a specified range)?

Upvotes: 0

Related Questions