Delfin
Delfin

Reputation: 607

How to use sum operator of rxjs?

Things I have tried include following where values is array of values of which I want to find the sum.

I have also added necessary functions from rxjs as follows: I get an error saying

typeError: Rx.Observable.from(...).sum is not a function

const { merge , interval ,from} = rxjs;
const { tap ,take ,sum } = rxjs.operators;   
             
var sumSource = Rx.Observable.from(values).sum(function (x) {
    return x;
});

var subscription = sumSource.subscribe(
    function (x) {
        console.log('Next: ' + x);
        x.target.value = x;
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    }
);

Not much is available about sum on internet.Any inputs to fix and get the sum?

Upvotes: 5

Views: 5728

Answers (1)

Jonathan Stellwag
Jonathan Stellwag

Reputation: 4267

  • sum: regarding the official rxjs github repository they do not export/provide the sum operator anymore.
  • reduce operator reduce applies an accumulator function over the source Observable, and returns the accumulated result when the source completes.
  • scan operator scan applies an accumulator function over the source Observable and returns the accumulated result every emit.

setup

const values = [1,2,3,4,5];
const accumulator = (acc, curr) => acc + curr;

implement reduce

from(values).pipe(
  reduce(accumulator, 0)
)
// Expected output: 15

implement scan

from(values).pipe(
  scan(accumulator, 0)
)
// expected output: 1, 3, 6, 10, 15

I made a running stackblitz here.

Upvotes: 3

Related Questions