Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Observable operations called once (duplicated) for every subscriber?

Each time I call .subscribe() on an Observable, the processing on each value is restarted (in the example below, the map function will be called twice for each value).

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);

Is there any way to have subscribe give you the processed value without rerunning the whole processing functions?

like image 799
Simon Boudrias Avatar asked Sep 26 '22 18:09

Simon Boudrias


1 Answers

Hi @Simon Boudrias You should know about 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 ..

In your case you can use publish with connect or refCount

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();
like image 62
xgrommx Avatar answered Sep 29 '22 06:09

xgrommx