Skip to content
jshacks.dev
Async

RxJS for Developers Who Already Know Promises

Learn RxJS 7 by mapping what you know about promises, async await and Promise.all to observables, operators, subscriptions and unsubscribe.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Node.js, Apache Kafka and RabbitMQ logos.

If you are comfortable with promises, you already understand most of the ideas in RxJS, under different names. A promise represents one future value, and an observable represents any number of them. A then chain becomes a pipe of operators. Promise.all becomes forkJoin and combineLatest. await becomes firstValueFrom. The things that are new are laziness, cancellation by unsubscribing and the large library of operators for time, which is where RxJS earns its keep. This post maps the vocabulary one concept at a time on RxJS 7, with printed output, so you can read observable code without relearning asynchronous programming from scratch. It stops short of the operator catalog, and the individual operators have their own posts, starting with map.

The vocabulary map

In promisesIn RxJS
new Promise((resolve, reject) => ...)new Observable((subscriber) => ...)
resolve(value)subscriber.next(value) then subscriber.complete()
reject(error)subscriber.error(error)
.then(fn).pipe(map(fn)) or .subscribe(fn)
.catch(fn)catchError(fn)
.finally(fn)finalize(fn)
await pawait firstValueFrom(o) or lastValueFrom(o)
Promise.all([...])forkJoin([...]) (waits for completion)
Promise.race([...])race(...)
Promise.resolve(x)of(x)

Keep this table in mind, and most RxJS code becomes readable.

Creating and subscribing

An observable is a recipe, and subscribe runs it.

JavaScript
import { of } from "rxjs";

const numbers = of(1, 2, 3);

numbers.subscribe({
  next: (value) => console.log("value:", value),
  error: (error) => console.log("error:", error.message),
  complete: () => console.log("done"),
});
Text
value: 1
value: 2
value: 3
done

The three callbacks correspond to a promise's fulfillment, rejection and the fact that a stream can end. A promise has no complete, because it has one value and finishing is implied.

Laziness: the first real difference

A promise starts working when you create it. An observable starts when you subscribe, and again for every new subscriber.

JavaScript
import { Observable } from "rxjs";

const promise = new Promise((resolve) => {
  console.log("promise executor runs now");
  resolve("promise value");
});

const observable = new Observable((subscriber) => {
  console.log("observable producer runs on subscribe");
  subscriber.next("observable value");
  subscriber.complete();
});

console.log("after creating both");

observable.subscribe((value) => console.log(value));
observable.subscribe((value) => console.log(value));
Text
promise executor runs now
after creating both
observable producer runs on subscribe
observable value
observable producer runs on subscribe
observable value

The promise executor ran at creation, once. The producer ran at each subscribe. Any code that wraps an HTTP call in an observable must keep that in mind: two subscriptions make two requests, unless you share the result with shareReplay.

then becomes pipe

Chaining transformations is done with pipe and operators, and each operator returns a new observable, the way each then returns a new promise.

JavaScript
import { of } from "rxjs";
import { map, filter } from "rxjs/operators";

of(1, 2, 3, 4, 5)
  .pipe(
    filter((n) => n % 2 === 1),
    map((n) => n * 10),
  )
  .subscribe((value) => console.log(value));
Text
10
30
50

The difference from a promise chain is that the values flow one at a time, and map runs once per value, not once for the whole result. This is the reason operators exist: a stream of values needs operations on each element, filtering, buffering, timing and combining, that a single-value promise never needed.

Flattening: then that returns a promise

In a promise chain, returning a promise from then makes the chain wait for it. In RxJS, when a map returns an observable you get an observable of observables, and you flatten it with an operator that decides how to combine the inner streams. switchMap, mergeMap, concatMap and exhaustMap are four answers to "what if a new value arrives while the previous inner observable is still running?".

JavaScript
import { of, timer } from "rxjs";
import { concatMap, map } from "rxjs/operators";

of("a", "b")
  .pipe(
    concatMap((letter) => timer(10).pipe(map(() => letter.toUpperCase()))),
  )
  .subscribe((value) => console.log(value));
Text
A
B

concatMap waits for each inner observable to complete before starting the next, which is the same as sequential await in a loop. mergeMap starts them all, the way Promise.all does. switchMap cancels the previous inner observable when a new value arrives, the behavior you want for search-as-you-type, and one that promises cannot express. The four have their own posts.

Error handling

An error terminates an observable for that subscriber, the way a rejection ends a promise chain. catchError is the catch equivalent, and it must return an observable, usually a fallback.

JavaScript
import { throwError, of } from "rxjs";
import { catchError } from "rxjs/operators";

throwError(() => new Error("request failed"))
  .pipe(catchError((error) => of(`fallback after: ${error.message}`)))
  .subscribe((value) => console.log(value));
Text
fallback after: request failed

Place catchError carefully in a long-lived stream. If it sits at the outer level, one error completes the whole stream, and the stream is dead. Put it inside the inner observable, so that an error in one request is handled and the outer stream keeps going.

Going back to await

You can always return to promises at the edge of an observable pipeline.

JavaScript
import { firstValueFrom, lastValueFrom, of } from "rxjs";

const stream = of(1, 2, 3);

console.log(await firstValueFrom(stream));
console.log(await lastValueFrom(stream));
Text
1
3

firstValueFrom resolves with the first emission and then unsubscribes. lastValueFrom waits for completion and resolves with the last value, and both reject if the observable errors or, for an empty observable, completes without a value unless you pass a defaultValue. The legacy toPromise() method was removed in RxJS 8, so use these.

Combining

The Promise.all analogue depends on what you want.

JavaScript
import { forkJoin, combineLatest, of, timer } from "rxjs";
import { map } from "rxjs/operators";

const a = timer(10).pipe(map(() => "a"));
const b = timer(20).pipe(map(() => "b"));

forkJoin([a, b]).subscribe((values) => console.log("forkJoin:", values));

combineLatest([of(1), of(2)]).subscribe((values) => console.log("combineLatest:", values));
Text
combineLatest: [ 1, 2 ]
forkJoin: [ 'a', 'b' ]

forkJoin waits for every input to complete and emits their last values once, the closest match to Promise.all. combineLatest emits each time any input emits, using the latest value from each, which is for values that change over time. The combineLatest line printed first because its inputs emit immediately, and the forkJoin timers took 20 ms.

Cancellation

This is the second real difference. A subscription can be cancelled, and the producer's cleanup runs.

JavaScript
import { interval } from "rxjs";

const subscription = interval(10).subscribe((n) => console.log("tick", n));

setTimeout(() => {
  subscription.unsubscribe();
  console.log("unsubscribed");
}, 35);
Text
tick 0
tick 1
tick 2
unsubscribed

The interval was cleared when the subscription ended. In a framework, forgetting to unsubscribe from a long-lived observable, such as a timer or a store, is the classic RxJS leak. The tools are the takeUntil operator, which completes a stream when another emits, the async pipe in Angular templates, and a Subscription object that collects several subscriptions to unsubscribe together.

Subjects: a promise you can resolve from outside

A Subject is an observable you can push values into, so it is both a producer and a stream, similar to a deferred promise.

JavaScript
import { Subject } from "rxjs";

const subject = new Subject();

subject.subscribe((value) => console.log("first:", value));
subject.next("a");

subject.subscribe((value) => console.log("second:", value));
subject.next("b");
Text
first: a
first: b
second: b

The second subscriber missed a. A BehaviorSubject holds the latest value and gives it to new subscribers, and a ReplaySubject replays several. Those are the usual tools for sharing state.

When RxJS is worth it

Reach for it when the problem is about sequences over time: debounce a search box and cancel stale requests, coordinate several event sources, retry with growing delays or manage a websocket with reconnects. Avoid it for one-shot async calls, where a promise is shorter and clearer, and for simple event handling that a listener covers. The bundle cost is also real, so import operators from rxjs directly and let your bundler remove the unused ones.

How to learn the rest

Do not try to memorize the operator list. Learn the handful that cover most real code: map, filter, tap, switchMap, mergeMap, concatMap, catchError, debounceTime, distinctUntilChanged and takeUntil. Everything else is a variation. When you have a problem, describe it in the vocabulary of time, such as "ignore values that arrive within 300 ms of each other" or "cancel the previous request when a new one starts", and look for the operator whose description matches. The official operator decision tree on the RxJS site does the same job and is worth bookmarking.

Marble diagrams, the lines with dots and arrows used throughout the documentation, are the best way to read an operator's behavior at a glance, and they are also how RxJS tests describe expected streams with TestScheduler. Learning to read them takes ten minutes and pays back for as long as you use the library.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.