gpt4 book ai didi

javascript - 为每个订阅在扫描运算符上创建一个新的种子对象

转载 作者:行者123 更新时间:2023-11-30 09:29:27 24 4
gpt4 key购买 nike

RxJS 5.5.2

我有以下代码将数字数组拆分为一个对象,该对象具有 2 个属性 'small' 用于小于 4 的数字,'big' 用于休息。

const o = from([1, 2, 3, 4, 5, 6]).pipe(
scan<number, {}>((a, b) => {
if (b < 4) {
a['small'].push(b);
} else {
a['big'].push(b);
}
return a;
}, {
'small': [],
'big': []
})
);
console.log('subscription 1');
o.subscribe(x => console.log(JSON.stringify(x)));
console.log('subscription 2');
o.subscribe(x => console.log(JSON.stringify(x)));

订阅 1 控制台打印后:

{"small":[1,2,3],"big":[4,5,6]} // this is ok

订阅后 2 个控制台打印:

{"small":[1,2,3,1,2,3],"big":[4,5,6,4,5,6]} // this is not ok

有没有办法在每次有人订阅时从一个新的种子对象开始?

最佳答案

另一种选择是将管道包装在 defer block 中,这将在订阅时重建源流。

defer(() =>
from([1, 2, 3, 4, 5, 6]).pipe(
scan<number, {}>((a, b) => {
if (b < 4) {
a['small'].push(b);
} else {
a['big'].push(b);
}
return a;
}, {
'small': [],
'big': []
})
)
);

每个订阅都会调用延迟 block 中的方法并订阅结果。尽管正如 @arturgrzesiak 所提到的,变异数组被视为函数式编程中的反模式,并被扩展为函数式响应式(Reactive)编程。

关于javascript - 为每个订阅在扫描运算符上创建一个新的种子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47238274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com