Search code examples
angularrxjsobservablesubscribereactivex

Why does the origin observable emits values, if an observable returned by an operator gets subscribed?


A cold observable needs to be subscribed that it emits values. When using an operator such as map a new observable gets returned.

const origin$ = Rx.Observable.from([1,2,3,4]);
const mapped$ = origin$.map(val => val+1);
mapped$.subscribe(console.log);

With .subscribe the mapped$ observable the values get emitted and get logged in the console.

But in this case the mapped$ observable got subscribed and not the origin$ observable. Why does the origin$ observable starts to emit values?


Solution

  • Using any operator(oldfashioned with .map() or nowadays with .pipe(map())) does not return a subscription. Instead it returns a new observable which takes the other observable as a source but waits with any subscription until it has a subscription.