RxJS reduce a ReplaySubject

Viewed 1678

I'm using ReactiveX/RxJS version.

Lets say that I have a Rx.ReplaySubject that every 2 seconds it emits an object that contains an id and an array with values. I want to reduce this array of values and get the sum of them all.

The problem is that ReplaySubject is a hot observable and it never completes, at least I don't want it to complete because I want the sum of that object values every 2 seconds. But in order to use the reduce operator the observable should be completed. So, how should I proceed ?

E.G not working code:

var subject = new Rx.ReplaySubject();

subject.
  map(x => x.transactions).
  // Reduce never concludes because ReplaySubject instance is not completed
  reduce((v1, v2) => v1+v2, 0).
  subscribe(function (value) {
    console.log(value)
  });

setInterval(injectData, 2000);

function injectData () {
  subject.next({id: Date.now(), transactions: [
    {value: Math.round(Math.random() * 5000)},
    {value: Math.round(Math.random() * 5000)},
    {value: Math.round(Math.random() * 5000)},
    {value: Math.round(Math.random() * 5000)},
    {value: Math.round(Math.random() * 5000)}
  ]});
}
1 Answers
Related