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

Each time I call .subscribe() on an Observable, the processing of 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 a way to subscribe to give you the processed value without restarting all processing functions?

+5
source share
1 answer

Hi @Simon Boudrias You Should Know About Cold vs. Hot Observables .

Cold observables start to run by subscription, i.e. the observed sequence only begins to push the values ​​to the observers when the Subscribe function is called. Values ​​also do not apply to 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(); 
+4
source

All Articles