每次我在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);

有什么方法可以让订阅给您带来已处理的值(value),而无需重新运行整个处理功能?

最佳答案

@Simon Boudrias嗨,您应该了解Cold vs. Hot Observables



在您的情况下,您可以将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();

10-08 04:59