Convert a generator function to and RxJs Observable
ES6 generator functions (function*()
) are great when you need fine control over how a collection is created. RxJs, on the other hand, offers a comprehensive set of operators to work with element streams.
Get the best of both worlds by defining the base structure using a generator function and use RxJs for further processing.
For example, a Fibonacci sequence is a textbook example of a collection that benefits from generators:
const fibonacciGen = function*() {
let v1 = 1;
let v2 = 1;
while(true) {
const res = v1;
v1 = v2;
v2 = v1 + res;
yield res;
}
};
This generates an infinite collection, but RxJs has no problems with it. But keep in mind to exercise caution and always include a limiting operator (for example, take
) for constructs like this.
To convert it to an observable sequence, use it like any other collection:
const fibonacciObservable = rxjs.from(fibonacciGen());
This way the rich API of RxJs is available.
As an illustration, let's find out the sum of the first ten even Fibonacci numbers:
fibonacciObservable // [1, 1, 2, 3, ...]
.pipe(
filter((e) => e % 2 === 0), // [2, 8, 34, 144, ...]
take(10), // [2, 8, 34, ..., 832040]
reduce((acc, e) => acc + e, 0) // [1089154]
)
.subscribe(console.log.bind(console));