How to create an infinite Observable that produces random numbers at random intervals?

For a function that generates random numbers, how would you create an infinite Observable that produces random numbers at random intervals?

function getRandomNumber() { // Assume this function returns a random number, eg 198 } function getRandomDelay() { // Assume this function returns a random delay in ms, eg 2000 } 

Here is an example of a desired observation:

 ---198--------64-------3---2----------18-------> (indefinitely) 3ms 7ms 6ms 3ms 10ms 
+5
source share
2 answers
 const { Observable } = require("rxjs"); const ob = new Observable(sub => { let timeout = null; // recursively send a random number to the subscriber // after a random delay (function push() { timeout = setTimeout( () => { sub.next(getRandomNumber()); push(); }, getRandomDelay() ); })(); // clear any pending timeout on teardown return () => clearTimeout(timeout); }); ob.subscribe(console.log); 
+6
source

Alternatively, if you do not want to live in a confusing timeout, you can write this completely as a stream:

 // the stream const randomizer$ = Rx.Observable.of("") .switchMap(() => Rx.Observable .timer(getRandomDelay()) .mapTo(getRandomNumber())) .repeat(); // subscribe to it randomizer$.subscribe(num => console.log("Random number after random delay" + num)); // your utility functions function getRandomNumber() { return ~~(Math.random() * 200) } function getRandomDelay() { return Math.random() * 1000 } 

A working example is here: http://jsbin.com/zipocaneya/edit?js,console


Alternative: First create a random number and then add a delay (if the runtime doesn't matter)

 // the stream const randomizer$ = Rx.Observable.of("") .switchMap(() => Rx.Observable .of(getRandomNumber()) .delay(getRandomDelay() ) .repeat(); // subscribe to it randomizer$.subscribe(num => console.log("Random number after random delay" + num)); 

Note: Since a concurrency or async operation is performed off-stream, you can simply use concatMap or flatMap - in this case they all work the same way.

+6
source

Source: https://habr.com/ru/post/1262056/


All Articles