LiveLoveApp logo

Marble Syntax

Marble Diagrams

Let's quick review the marble diagrams that are used by the official documentation for RxJS.

Marble Diagram

The important things to note are:

  • The arrow represent notifications over time.
  • Each "marble" represents a next notification.
  • The pipe ( | ) represents a completion notification.
  • The "X" represents an error notification.

Marble Syntax

We'll use a string syntax to represent an Observable and Subscriptions. This string syntax is meant to model an Observable, or Subscription, over time. The beauty of marble testing with Observables is that we can synchronously test asynchronous Observables.

Let's start with a few of the basics of the marble string syntax and what each character(s) represent:

  • Whitespace is ignored.
  • - A dash represents a frame.
  • [a-z0-9] a next notification.
  • | A completion notification.
  • # An error notification.

Next, let's discuss the use of time progression in the marble strings. As mentioned above, we can use the dash ( - ) to represent the progression of a single frame. One frame is equal to one virtual milliseconds.

If we need to create a marble string that represents an Observable that emits after many milliseconds, or perhaps even, seconds, or minutes, we can do so using a specific time progression syntax. There is no need to include hundreds or thousands of dashes in our marble strings. Let's look at some example of time progression values:

  • [0-9]ms represents N number of milliseconds.
  • [0-9]s represents N number of seconds.
  • [0-9]m represents N number of minutes.

Finally, we can group together notifications that occur in the same frame using parenthesis. For example, our Observable may emit a notification and complete in the same frame: (a|).

Examples

First, let's define a new marble string that represents a cold Observable that emits 3 values and then completes:

const source = cold('a-b-c-|');

Let's break this down:

  • A next notification on frames 0, 2, and 4.
  • The Observable completes on frame 6.

Next, let's describe a cold Observable that emits an error after 1000 milliseconds:

const source = cold('1000ms #');

Finally, here is an example of a cold Observable that emits a next notification and completes in the same frame after 1000 millisconds:

const source = cold('1000ms (a|)');