RxJs

August 29, 2023 · 4 min readLucian Ciobanu
Tags:RxJS

I've recently joined a project as Angular Developer for a fintech initiative of one of the big four audit companies and I was challenged by the depth of RxJs used on the project for the interface. It was the first time I had to work with higher order observables so I had to recap on my knowledge. Here are some of my takeaways:

Reactive programing is a declarative programming paradigm concerned with data streams and the propagation of change.

Observables are lazy push collections of multiple values. An observable is a lazily evaluated computation that can synchronously or asynchronously return zero to (potentially) infinite values from the time it's invoked onwards. A promise is a computation that may (or may not) eventually return a single value.

Observables deliver: 'next' notifications with values such as Number, String or Objects; 'error' notifications which send a JavaScript error or exception, 'complete' notification which does not send a value.

An observer is a consumer of values delivered by an observable and are simply a set of callbacks, one for eacht type of notification delivered by the observable.

Hot observables push events or values even when no one is subscribed to them like an observable based on mouse clicks or keyboard events. Cold observables only emit values on subscription like an HTTP call to an endpoint and no values are missed in case of a cold observable.

Subject(s) is a special type of observable that allows values to be multicasted to many observables while plain observables are unicast. BehaviorSubject has a notion of the "current value" as it stores the latest value emitted to its consumers and whenever a new observer subscribes, it will immediately receive the current value. ReplaySubject is similar to a BehaviorSubject in that it can send old values to new subscribers, but it can also record a part of the observable execution.

Testing with Marbles

We can test our asynchronous RxJS code synchronously and deterministically by virtualizing time using the TestScheduler. Marble diagrams provide a visual way for us to represent the behavior of an Observable. We can use them to assert that a particular Observable behaves as expected, as well as to create hot and cold Observables we can use as mocks.

Basics of the marble progression syntax and what each character(s) represent:
• whitespace is ignored.
• - dash represents a frame.
• [a-z0-9] a next notification.
• |  completion notification.
• #  n error notification.

The subscription marble syntax:
• '-' time: 1 frame time passing.
• [0-9]+[ms|s|m] time progression: It's a number, followed by ms, s or m; e.g. a 10ms b
• '^' subscription point: shows the point in time at which a subscription happens.
• '!' unsubscription point: shows the point in time at which a subscription is unsubscribed.

Higher Order Observables

import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';

const higherOrderObservables = new Observable((observer) => {
  let i = 0;
  const add = new Observable((_observer) => _observer.next(i++ * 10));
  const handle = window.setInterval(() => observer.next(add), 1000);
  returon () => window.clearInterval(handle);
});

higherOrderObservable
  .pipe(
    switchMap((observable: Observable<number>) =>
      observable.pipe(tap(console.log))
    )
  )
  .subscribe();

• First we create a new Observable instance. ("outer" Observable)
• Then, we declare i to start with 0.
• The add constant is a new Observable that emits a next notification that multiplies the incremented i value by 10. ("inner” observable)
• We use window.setInterval() to emit to the Observer the inner add Observable every 1000 milliseconds.
• When the outer Observable is unsubscribed from the teardown function is invoked, which clears the interval.
• Finally, we subscribe to the outer Observable. The switchMap() operator receives an Observable as the next notification. The switchMap() subscribes to the inner Observable and maps to the next notification emitted by the inner Observable.

Something I was really glad to find during my research is the rxjs decision tree which recomends more complex operators to be used. This can be found at http://rxjs.dev/operator-decision-tree

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery