Doua Beri
Doua Beri

Reputation: 10949

Use reduce Subject without calling complete

I'm new to RxJS. I'm using RxJs 5.5.2

To keep it simple I want to return the reduced value every time I called next on a subject. Here is a sample code:

const sub = new Subject<number>();
const obsesvable = sub.pipe(
  reduce((a, b) => {
    return a + b;
  }, 0)
);

obsesvable.subscribe(x => console.log(x));

sub.next(2);
sub.next(3);
// if I don't call this nothing happens
sub.complete();

Now if I don't call sub.complete() nothing happens.

If I call sub.complete() I can't send values any more with sub.next();

Upvotes: 0

Views: 49

Answers (1)

maxime1992
maxime1992

Reputation: 23793

Take a look to the marble diagram of reduce method.

enter image description here

It'll only emit when the stream is ended, that's why you don't have anything until you call complete.

If you want to "reduce" and get the values over time you should rather use scan: enter image description here

So your code should rather be:

const sub = new Subject<number>();
const obsesvable = sub.pipe(
  scan((a, b) => {
    return a + b;
  }, 0)
);

obsesvable.subscribe(x => console.log(x));

sub.next(2);
// output: 2
sub.next(3);
// output: 5

Upvotes: 1

Related Questions