How can i create an observable sequence of random numbers within a range using the rxjs observable?
I can iterate over a range using range.
For example:
Observable.range(0, 20)
.flatMap(data => getImage(data))
.map(data => this.image = data);
However, i would like to have it continuously generate a random number for the sequence until i force it to stop. Not just iterate through the values until it is done.
NOTE: I am using rxjs 5. Which does not have a while.
This will generate the random number within intervals of time. This is exactly what i needed.
let mySubscription: Subscription<number> = Observable.interval(3000)
.map(data => generateRandomNumber(...))
.subscribe(
data => console.log(data),
error => console.log(error),
() => console.log("complete")
);
To stop the observer, simply unsubscribe from the subscription.
mySubscription.unsubscribe();
generateRandomNumber() is a method that just generates a random number for me. It is out of scope of the issue.
If you have access to generator functions you could do something like this using Observable.from: (Typescript support)
jsbin
function* generator(min, max){
while (true) {
yield Math.random() * (max - min) + min;
}
}
Rx.Observable.from(generator(0, 9000))
.take(42)
.subscribe(value => console.log(value));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With