Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Observable: Take a random number of integers
function* range(from, to) {
for (let i = from; i <= to; ++i) {
yield i;
}
}
function take(source, n) {
if (n <= 0) {
return Observable.from([]);
}
return new Observable(sink => {
let count = 0;
return source.subscribe({
next(v) {
sink.next(v);
if (++count === n) {
sink.complete();
}
},
error(e) { sink.error(e) },
complete() { sink.complete() },
});
});
}
let observable = take(
Observable.from(range(0, Number.POSITIVE_INFINITY)),
Math.round(Math.random() * 100)
);
observable.subscribe(console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.