Reputation: 17762
I have one Observable, obs1, which represents a stream of numbers over time. I need to accumulate the sum of such numbers and emit it progressively (i.e. a long way to say I need to use scan
operator).
Then there is a second Observable, obs2, that represents some sort of "reset time". In other words, when obs2 emits, I have to reset the accumulator I have set on obs1 and start summing from 0.
I think I have been able to reach the behavior I want with the following code, but I am not sure it is the right way to do it (it sorts of smells to me)
const obs1 = Observable.interval(100).mapTo(1).take(100);
const obs2 = Observable.interval(700).take(10);
obs1.pipe(
windowWhen(() => obs2),
mergeMap(d => d.pipe(scan((acc, one) => acc + one, 0)))
)
.subscribe(console.log);
Any suggestion on how to improve it?
Upvotes: 4
Views: 1377
Reputation: 17762
Probably something like this is what i was looking for
const obs1 = Observable.interval(100).mapTo(1).take(100);
const obs2 = Observable.interval(700).take(10);
function scanReset(seed) {
return obs1.pipe(
scan((acc, one) => acc + one, seed)
)
}
obs2.pipe(
switchMap(() => scanReset(0))
)
.subscribe(console.log);
Upvotes: 4