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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With