gpt4 book ai didi

javascript - 为什么 Observable 操作对每个订阅者调用一次(重复)?

转载 作者:搜寻专家 更新时间:2023-11-01 04:15:26 26 4
gpt4 key购买 nike

每次我在 Observable 上调用 .subscribe() 时,对每个值的处理都会重新开始(在下面的示例中,map 函数将为每个值调用两次)。

var rx = require('rx-lite');
var _ = require('lodash');

var obs = rx.Observable.fromArray([1, 2]);

var processing = obs.map(function (number) {
// This function is called twice
console.log('call for ' + number);
return number + 1;
});

processing.subscribe(_.noop, _.noop);
processing.subscribe(_.noop, _.noop);

有没有办法让订阅给你处理后的值而不用重新运行整个处理函数?

最佳答案

嗨@Simon Boudrias 你应该知道 Cold vs. Hot Observables .

Cold observables start running upon subscription, i.e., the observable sequence only starts pushing values to the observers when Subscribe is called. Values are also not shared among subscribers ..

在您的情况下,您可以将 publishconnectrefCount 一起使用

var rx = require('rx-lite');
var _ = require('lodash');

var obs = rx.Observable.fromArray([1, 2]);

var processing = obs.map(function (number) {
// This function is called twice
console.log('call for ' + number);
return number + 1;
}).publish();

processing.subscribe(_.noop, _.noop);
processing.subscribe(_.noop, _.noop);

processing.connect();

关于javascript - 为什么 Observable 操作对每个订阅者调用一次(重复)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32556231/

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