RxJS - Logical Operators

01/30/2021, Sat
Categories: #JavaScript
Tags: #RxJS

Logical Evaluation

In traditional JavaScript, one would use the logical operators "&&", "||", "!" when evaluating variables for the "and", "or", and "not" conditions respectively. Similarly, there are RxJS operators which looks like the ones found in JavaScript when you wish to treat observable like values that needs to be compared against one another.

For the examples below, "true" in this sense refers to the observable have "truly" emitted a value and not have it base upon the actual underlying value within the observable.

AND

Use the "forkJoin" operator when every single observable must be activated for the subscription to run.

// When the observables will emit at least once in any order

import { forkJoin, of, interval } from 'rxjs';
import { take } from 'rxjs/operators';

const timer$ = interval(1000).pipe(take(1)),
  truthfulness$ = of(true);

forkJoin([
  timer$,
  truthfulness$
])
.subscribe(() => {
  console.log('All completed once');
});

Alternatively, you might be able to use "combineLatest" when you have long-lived observables. Tangentially, "concat" or "zip" will work if a strict order needs to be imposed for activation of observables in a series.

OR

The "race" operator emits when any observable within a group gets trigger.

// When the obervables will emit at least once in any order

import { of, interval, race } from 'rxjs';
import { take } from 'rxjs/operators';

const timer$ = interval(1000).pipe(take(1)),
  truthfulness$ = of(true);

race(
  timer$,
  truthfulness$
)
.subscribe((first) => {
  console.log('Truthiness first', first);
});

In addition to "forkJoin", "merge" can be used when order does not matter.

NOT

There is no negation operator you can directly use on an observable, but one can use the "map" operator and check against the negated value inside the observable.

import { of } from 'rxjs';
import { map } from 'rxjs/operators';

const truthfulness$ = of(true);

truthfulness$
  .pipe(
    map((theValue) => {
      return !theValue;
    })
  )
  .subscribe((negatedValue) => {
    console.log("Negated value:", negatedValue);
  });