Learning about the marble diagram – our secret weapon
RxJS ships with more than 100 operators. Operators are one of the building blocks of RxJS. They are very useful for manipulating streams. All the reactive patterns that will be detailed later in this book are based on operators. And when it comes to explaining operators, it is better to refer to a visual representation. And that's why there are marble diagrams. Thankfully!
Marble diagrams are a visual representation of the operator's execution. We will be using the marble diagram in all chapters to understand the behavior of RxJS operators. At first, it might seem daunting, but it is delightfully simple. First, you only have to understand the anatomy of the diagram and then you're good to read and translate it. You will be able to understand any RxJS operator – those used in this book along with others, too.
So as we said, marble diagrams represent the execution of an operator. So, every diagram will include the following:
- Input Observable(s): This represents one or many observables given as input to the operator.
- Operator: This represents the operator to be executed with its parameters.
- Output Observable: This represents the observable produced after the operator's execution:
Well, this is the big picture. Now, let's zoom in on the representation of the input/output observables. It includes the following:
- The timeline: Observables are asynchronous streams that produce data over time. Therefore, the representation of time is crucial in the marble diagram, and it is represented as an arrow flowing from left to right.
- The marble values: These are the values emitted by the observables over time.
- The completion status: The vertical line represents the successful completion of the observables.
- The error status: The X represents an error emitted by the observable. Neither values nor the vertical line representing the completion will be emitted thereafter:
That's all the elements you need to know. Now, let's put all of the pieces together into a real marble diagram:
Let's break down what is happening in the preceding diagram. As you might have guessed, we have a custom operator called divideByTwo
that will emit half of every received number. When the input observable emits the values of 4
and 8
, the output observable produces 2
and 4
, respectively.
However, when the value of R
, which is non-numeric, is emitted, then an error is thrown, indicating abnormal termination. This case is not handled in the operator code. The input observable continues the emission and then completes successfully. However, the value will never be processed because, after the error, the stream is closed.
At this level, we went through all of the elements composing the marble diagram. And you will be able to understand the operators used in the chapters to come.