I need some clarification regarding the efficiency of operator pipelines in RxJS.
Based on my current understanding, each operator within the pipeline receives an observable and generates a new (potentially modified) observable to pass on to the next operator. This process is similar to how JavaScript's filter, map, and reduce functions work, ensuring the original observable or array remains pure and untouched.
The RxJS Documentation supports this notion at: https://rxjs-dev.firebaseapp.com/guide/operators
A Pipeable Operator is a function that takes an Observable as its input and returns another Observable. It is a pure operation: the previous Observable stays unmodified.
When dealing with lengthy operator pipelines, the creation of intermediate observables may seem resource-intensive.
Furthermore, I am currently studying the book 'Reactive Programming with RxJS 5' by Sergi Mansilla. Although RxJS has advanced to version 6.5.3, the fundamental mechanisms are likely unchanged.
The book discusses the efficiency of pipelines, stating that they do not produce intermediate Observables. Instead, all operations are applied to each element simultaneously. For instance, the operator take(amount) completes the stream after extracting the initial amount of elements. Moreover, it mentions the concept of lazy evaluation, which involves traversing the source observable stream just once or until the take condition is met.
import * as rxCore from 'https://dev.jspm.io/rxjs@6/_esm2015/index';
import * as rxOps from 'https://dev.jspm.io/rxjs@6/_esm2015/operators';
const numberStream = rxCore.range(0, 10);
numberStream.pipe(
rxOps.map(number => number * number), //creates Observable with [0,1,4,9,16,25,36,49,64,81]
rxOps.filter(number => number % 2 === 0), //creates Observable with [0,4,16,36,64]
rxOps.take(3) //completes after [0,4,16]
).subscribe(console.log); //logs 0, 4, 16
Is there any generation of intermediate observables within this operator pipeline? Or does only the final pipeline create a new observable while leaving the numberStream unaffected? What exactly is happening in this scenario?