累积值,例如扫描,但可以随着时间的推移重置累加器 [英] accumulating values such as with scan but with the possibility to reset the accumulator over time
问题描述
我有一个 Observable,obs1,它代表随着时间推移的一系列数字.我需要累加这些数字的总和并逐步发出它(即说我需要使用 scan
运算符很长的路要走).
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).
然后是第二个 Observable,obs2,代表某种重置时间".换句话说,当 obs2 发出时,我必须重置我在 obs1 上设置的累加器并从 0 开始求和.
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);
有什么改进的建议吗?
推荐答案
大概这就是我要找的东西
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);
这篇关于累积值,例如扫描,但可以随着时间的推移重置累加器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!