[RxJS] Aggregating Streams with Reduce and Scan using RxJS

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.