Mastering Reactive JavaScript
上QQ阅读APP看书,第一时间看更新

Reading how an operator works

Throughout this book, you will see a lot of diagrams explaining how an operator works. These diagrams are a graphical representation of observables and operations in those observables. Usually, the diagrams consist of three parts. On the top they shows a line with balls representing the initial state of an observable. The line itself represents an observable. The circles are events that happened in this observable and they are pushed from left to right; therefore, the leftmost ball is the first event, the second one is the second, and so on. This is illustrated in the following diagram:

So, the preceding line represents an observable with three emitted events. The string at the center of each circle is the value emitted by that event. The short vertical line on the right-hand side of the diagram represents the end of this observable. This diagram is a graphical representation of the following observable:

Bacon 
.fromArray([
'First Event',
'Second Event',
'Third Event'
]);

As we know, an observable can exist forever (the ones created using the Bacon.interval() method). To represent this kind of observable, we remove the short line on the right-hand side. This way, we show that other events might happen in this observable in the future, but we are not interested in them, , as shown in the following diagram:

This diagram is a possible representation of the following observable:

Bacon 
.interval(1000);

Keep in mind, the time between events is irrelevant in this case, so we decided to omit it from the graphical representation (we usually omit this information, as this is an implementation detail). The Bacon.interval() method always emits an empty object, and for this reason, we draw brackets at the center of each circle.

The main reason for using this graphical representation is to show how an operator transforms an observable. So to show which operator is being used, we add an arrow pointing downward with the name of the operator and the content of the operator if needed. So if we want to represent the use of the map() operator, we can use the following diagram:

As discussed before, when an operator is applied to an observable, it creates a new observable (it does not change the original observable). For this reason, we add a new line that represents the new observable created after the operation. On this new line, I decided to omit the value at the center of the circle (adding only three dots), because the way the map() operator works is out of the scope of this discussion.

Sometimes we want to represent multiple operators. In such cases, we just keep chaining more lines. Some operators let you work with multiple observables, which makes the diagram more complex. But don't worry, we will explain the changes the first time they happen.