What is the RxJS equivalent of the Array reduce? What if I want to emit my reduced or aggregated value @ each event? This brief tutorial covers Observable operators reduce () and scan (), their differences and gotchas.
In ES5, the Array's reduce function works like this:
var ary = [0,1,2,3,4]; var res = ary.reduce (function(PreVal, item) { return preval+0 //ten
In RxJS, also have reduce function:
It gives the same result.
var source = Rx.Observable.fromArray ([0,1,2,3,4]); Source.reduce (function(PreVal, Item) { return preval+0). Subscribe (function(res) { console.clear (); Console.log (res);});
Let's do it async:
We'll wait for 2.5 seconds until it gives result "10". This means the reduce () function in RxJS, it would not exec until the observable finihsed.
var source = Rx.Observable.interval ($). Take (5); Source.reduce (function(PreVal, Item) { return preval+0). Subscribe (function(res) { console.clear (); Console.log (res);});
So if we just write:
var source = Rx.Observable.interval (500);
And never finish it, we won ' t get result by reduce () funtion.
Use SACN () function instead of the reduce () to get result for each time:
var source = Rx.Observable.interval ($). Take (5); Source.scan (function(preVal, item) { return preval+item;}). Subscribe (function(res) { console.log (res);}); /* 013610 */
When I run this, you'll see each time it ticks in, I get the next value, the next reduced value. One nice difference with scan though are, since it doesn ' t wait for completion, if I were to run this again, it ' s actually Going to give me a result every time.
[RxJS] Aggregating Streams with Reduce and Scan using RxJS