Skip to content
jshacks.dev
Async

The RxJS forkJoin Operator Explained With Examples

Learn how RxJS forkJoin waits for several observables to complete and emits their last values together, and which edge cases make it emit nothing.

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

forkJoin is Promise.all for observables. You hand it several sources, it subscribes to all of them at once, waits until each one completes, and emits a single array holding the last value of each. It then completes. That makes it the right tool for loading a page that needs a user, their settings and a list of projects before it can render. It also has two sharp edges: a source that never completes keeps it waiting forever, and a source that completes without emitting makes it finish with no output at all. This post explains forkJoin in RxJS 7 with printed output, covers the array and object forms, error behavior and those edge cases, and shows how to make it resilient.

What it does

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

forkJoin([
  of("user").pipe(map((x) => x.toUpperCase())),
  timer(100).pipe(map(() => "settings")),
  of(1, 2, 3),
]).subscribe({
  next: (result) => console.log(result),
  complete: () => console.log("complete"),
});
Text
[ 'USER', 'settings', 3 ]
complete

The third source emitted 1, 2 and 3, and only the last one, 3, appears. The slowest source decides when the result arrives, here about 100 ms. All three subscriptions started together, so the total time is the longest single time, not the sum.

The object form

Since RxJS 7, passing an object is the preferred style for named results, and the deprecated spread arguments are gone.

JavaScript
import { forkJoin, of } from "rxjs";

forkJoin({
  user: of({ id: 1, name: "Ada" }),
  projects: of(["alpha", "beta"]),
  flags: of({ beta: true }),
}).subscribe(({ user, projects, flags }) => {
  console.log(user.name, projects.length, flags.beta);
});
Text
Ada 2 true

Names beat positions. Reordering the sources never silently swaps two results.

Sources that never complete

forkJoin needs completion. A source such as interval, a subject or a websocket never completes by itself, and the combined stream then never emits.

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

forkJoin([of("ready"), interval(20).pipe(take(3))]).subscribe((v) =>
  console.log(v)
);
Text
[ 'ready', 2 ]

Without take(3) nothing would print, ever. For a state stream where you only want the current value once, use first() or take(1).

JavaScript
import { BehaviorSubject, forkJoin } from "rxjs";
import { first } from "rxjs/operators";

const a$ = new BehaviorSubject("A");
const b$ = new BehaviorSubject("B");

forkJoin([a$.pipe(first()), b$.pipe(first())]).subscribe(console.log);
Text
[ 'A', 'B' ]

Sources that complete without a value

If one source completes without emitting, forkJoin completes immediately and emits nothing, because it has no last value to use for that position.

JavaScript
import { EMPTY, forkJoin, of } from "rxjs";

forkJoin([of(1), EMPTY]).subscribe({
  next: (v) => console.log("next", v),
  complete: () => console.log("complete without a value"),
});
Text
complete without a value

This one hides bugs. An HTTP call that returns an empty stream, or a filter that removed everything, quietly produces no result for the whole group. A default fixes it.

JavaScript
import { EMPTY, forkJoin, of } from "rxjs";
import { defaultIfEmpty } from "rxjs/operators";

forkJoin([of(1), EMPTY.pipe(defaultIfEmpty(null))]).subscribe(console.log);
Text
[ 1, null ]

Errors: first one wins

If any source errors, forkJoin errors immediately and unsubscribes from the others. The values that had already arrived are lost.

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

forkJoin([
  timer(50).pipe(map(() => "slow ok")),
  throwError(() => new Error("boom")),
  of("fast ok"),
]).subscribe({
  next: (v) => console.log("next", v),
  error: (e) => console.log("error", e.message),
});
Text
error boom

To get partial results, catch inside each source, so that a failure becomes a value.

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

const safe = (source$) =>
  source$.pipe(catchError((e) => of({ error: e.message })));

forkJoin({
  a: safe(of("ok")),
  b: safe(throwError(() => new Error("boom"))),
}).subscribe(console.log);
Text
{ a: 'ok', b: { error: 'boom' } }

Now the group always completes with an entry for each source, and the caller decides how to treat the failed one.

forkJoin with HTTP

The classic use is loading several resources in parallel. With fromFetch, which completes after the response, or a promise-returning function wrapped in from, each source emits one value and completes.

JavaScript
import { forkJoin, from } from "rxjs";

const getUser = () => Promise.resolve({ name: "Ada" });
const getOrders = () => Promise.resolve([{ id: 1 }, { id: 2 }]);

forkJoin({ user: from(getUser()), orders: from(getOrders()) }).subscribe(
  ({ user, orders }) => console.log(`${user.name} has ${orders.length} orders`)
);
Text
Ada has 2 orders

Remember that a promise starts as soon as it is created, so from(getUser()) has already sent its request before forkJoin subscribes. Wrap in defer(() => getUser()) if you want the work to start on subscription, for instance when you may retry the observable.

forkJoin versus Promise.all

forkJoinPromise.all
Result shapearray or objectarray
Multiple values per sourcekeeps only the lastnot applicable
Cancel on unsubscribeyes, all sourcesno
Empty sourcecompletes silentlyresolves with undefined
Starts workon subscribe (cold)at creation

Cancellation is the practical advantage. If a component is destroyed before the group finishes, unsubscribing aborts every pending request, where Promise.all would keep them running.

Common mistakes

Using it with streams that never end. Add take(1) or first().

Not noticing an empty source. A silent completion looks like "no response yet". Use defaultIfEmpty or a throwIfEmpty guard.

Losing partial results to one error. Catch in each source.

**Reaching for forkJoin when you want live updates.** It emits once. If you need a new combination whenever one input changes, use combineLatest.

Passing an empty array. forkJoin([]) completes immediately with no value. Check for it when the list is built dynamically.

Designing for partial failure

The all-or-nothing nature of forkJoin is its biggest decision, and it is worth making on purpose. For a page that cannot render without all of its data, failing as a unit is correct: show one error state and offer a retry. For a dashboard made of independent panels, the same behavior is a poor experience, because one slow or broken service blanks the whole screen. In that case give each panel its own stream, or catch inside each source and return a marker that the panel can render as "unavailable". The group still completes, and the failed part is visible as a failed part.

A related choice is how long to wait. forkJoin waits for the slowest source, with no limit. A single service that hangs holds the whole group hostage. Adding a timeout to each source turns a hang into an error you can handle, and a sensible budget per source is usually a better design than one global wait. Pick the budget from what the user will tolerate, not from the typical response time.

Ordering and side effects

The sources inside forkJoin start in the order you list them, but they finish in whatever order the network decides, and the output array always keeps the order you listed. Code that reads result[0] and result[1] is therefore stable, even though the requests overlapped. If the sources have side effects, such as incrementing a counter or writing a log line on subscription, remember that all of them happen before the first result arrives, not one after another.

Replacing it with async and await

Many teams now write the same logic with Promise.all and await, and for one-shot requests that is fine. The reasons to keep forkJoin are cancellation and composition: you can unsubscribe to cancel every request at once, and you can pipe the result into other operators such as switchMap without leaving the stream. If neither matters in a given function, the promise version has fewer concepts and is easier for a newcomer to read.

Typing the result

In TypeScript, the object form of forkJoin preserves the type of each source under its key, so result.user is the user type and result.projects is the projects type without any casts. The array form infers a tuple, which also works, but the object form survives refactoring better, since adding a source does not shift the position of the others. When you wrap a source with catchError to return a marker value, the type of that entry becomes a union of the success type and the marker, and the compiler will then insist that the consumer handle both, which is exactly the discipline you want.

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.