Visualizing Observables

You’re about to learn some of the operators that we’ll use most frequently in our RxJS programs. Talking about what operators do to a sequence can feel abstract. To help developers understand operators in an easy way, we’ll use a standard visual representation for sequences, called marble diagrams. They visually represent data streams, and you will find them in almost every resource for RxJS.

Let’s start with the range operator, which returns an Observable that emits all integers within a specified range: Rx.Observable.range(1, 3);

The marble diagram for it looks like this:

images/ch3_marble_range.png

The long arrow represents the Observable, and the x-axis represents time. Each circle represents a value the Observable emits by internally calling next(). After generating the third value, range calls complete, represented in the diagram by a vertical line.

Let’s now look at an example that involves several Observables. The merge operator takes two different Observables and returns a new one with the merged values. The interval operator returns an Observable that yields incremental numbers at a given interval of time, expressed in milliseconds.

In the following code we’ll merge two different Observables that use interval to produce values at different intervals:

 const​ a$ = Observable.interval(200).map(i => ​`A​${i}​`​);
 const​ b$ = Observable.interval(100).map(i => ​`B​${i}​`​);
 
 Observable.merge(a$, b$).subscribe(x => {
  console.log(x);
 });
<= B0, A0, B1, B2, A1, B3, B4...

The marble diagram for the merge operator looks like this:

images/ch3_marble_merge.png

Here, the dotted arrows along the y-axis point to the final result of the transformation applied to each element in sequences A and B. The resulting Observable is represented by C, which contains the merged elements of A and B. If elements of different Observables are emitted at the same time, the order of these elements in the merged sequence is random.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.5.86