Reputation: 10949
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
Reputation: 23793
Take a look to the marble diagram of reduce
method.
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:
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