| | |

RxJS 12 ๐ŸŸฃ Memory Leaks & Cancellation โ€” Managing lifecycles with takeUntil, Subscription composition, and AbortSignal

โฑ๏ธ Estimated read: 27 min | |

Every subscribe() call in RxJS creates a live connection between a Subscriber and whatever produced the values. That connection holds a reference to your next callback, and through it to everything the callback closes over โ€” the component instance, the DOM node, the socket. When the source is finite, the connection tears itself down on completion and nothing else is required. When the source is not finite โ€” an interval, a fromEvent, a Subject, a WebSocket, a store slice โ€” the connection stays open until something explicitly closes it. Nothing in RxJS closes it for you, and nothing warns you when you forget.

This is the fundamental asymmetry of reactive code: subscribing is a single call that feels like reading a value, but it is actually starting a process. A memory leak in RxJS is rarely a bug in the library; it is almost always a started process that was never stopped. The symptom is usually not a crash but a slow accumulation: duplicate HTTP requests, handlers that fire two, three, ten times for what should be one event, and a heap that climbs in a way that only shows up after ten minutes of use.

The chapter starts by identifying what actually leaks โ€” the subscriber, not the observable โ€” and then works through the four mechanisms that stop it. First, the takeUntil notifier, which is the general-purpose answer for any stream that must die with a lifecycle. Second, Subscription composition, which lets you hold a whole group of streams with one object and end them with one call. Third, the AbortSignal bridge, which is how cancellation crosses out of RxJS and into fetch, addEventListener, and any other web API that speaks the platform’s cancellation protocol. And fourth, the operators that already own their inner subscriptions, which are the cases where you should not write any teardown code at all, because writing it hides the fact that the correct operator was already doing it.

Key point: RxJS does not cancel anything for you. A Subscription lives until it is unsubscribed or its source completes, so every long-lived stream needs an explicit owner of its lifetime โ€” a takeUntil notifier, a parent Subscription, or an AbortSignal โ€” and the choice of which one belongs to where the stream’s data comes from, not to a house style.


Why cancellation exists

The subscriber is a registered observer. When you call subscribe(), RxJS constructs a Subscriber object, passes it to the source’s subscribe function, and the source โ€” interval, a Subject, fromEvent โ€” stores it in a list. That list is the source’s memory of who is listening. For of(1, 2, 3) the list is emptied after three values because the source completes. For interval(1000) the list is never emptied, because the source has no reason to stop producing. If nothing calls unsubscribe, the entry stays in that list for the remainder of the page’s life, and so does every reference reachable from it.

A leak here is a process that keeps running. JavaScript’s garbage collector can only reclaim what is unreachable. A setInterval whose id is still registered is reachable from the runtime’s timer table. A subscriber in a Subject‘s observer list is reachable from the Subject. A fetch connection is held open by the network stack. In each case, the memory is not leaking in the classic sense โ€” it is being actively retained by something that is still doing work. That is why these bugs surface as duplicated side effects long before they surface as heap growth.

Cancellation has a cost, so it must be opt-in. An observable cannot know whether the consumer wants one value or a million. If RxJS unsubscribed automatically after some heuristic, every stream that legitimately runs for the lifetime of the app โ€” a router event source, a websocket feed โ€” would break. The library’s contract is therefore the honest one: you started it, you stop it. The cost is discipline; the benefit is that cancellation is always explicit, always predictable, and never happens behind your back at an arbitrary moment.

Teardown is not the same as completion. A stream that completes has finished producing. A stream that is unsubscribed is being stopped whether or not it had finished. These are different events with different downstream consequences, and RxJS keeps them separate: complete handlers run for completion, finalize runs for both, and an aborted AbortSignal is neither โ€” it is an error path. Every leak-prevention tool in this chapter is a different answer to the question “which of these three events should this stream’s death be?”

The boundary with the platform is where leaks escape RxJS. When a subscription wraps a browser resource โ€” an HTTP request, a socket, an event listener โ€” unsubscribing from the observable does not automatically close the underlying resource unless the adapter was written to do so. fromFetch was written to do so, via AbortSignal. A hand-rolled new Observable(...) that calls fetch without wiring the teardown does not, and the request stays alive after the subscription is gone. The subscription is freed; the resource is not.


a. What actually leaks

The object that leaks is the Subscriber, and the thing that makes it expensive is the closure it holds. If the next callback references this, the leaked subscriber keeps the entire enclosing object alive โ€” its fields, its DOM references, its own child subscriptions. A single forgotten subscription in a component that is created and destroyed a hundred times holds a hundred component instances in memory.

import { interval } from "rxjs";

// subscribe() constructs a Subscriber and hands it to `interval`, which
// stores it in the list of observers it will notify on every tick.
const sub = interval(1000).subscribe((n) => {
  // This callback closes over everything in the enclosing scope.
  console.log("tick", n);
});

// The interval is still registered with the runtime timer table, and the
// Subscriber is still in the observer list. Both stay reachable.
sub.unsubscribe();
// Only now is the subscriber detached and the timer cleared.

The contrast with a finite source is the whole reason leaks are easy to miss: the same code, written against a source that completes, needs no teardown at all.

import { of, from } from "rxjs";

// `of` emits its arguments and completes immediately. Completion closes the
// Subscription, so the observer list is emptied without any manual call.
of(1, 2, 3).subscribe({
  next: (v) => console.log(v),          // 1, 2, 3
  complete: () => console.log("done"),  // runs, and the Subscriber detaches
});

// The same applies to any finite source: an HTTP response, a promise,
// a `timer()` that emits once, `first()`, `take(n)`.
from(Promise.resolve("value")).subscribe((v) => console.log(v));

The dangerous sources are a short and well-known list: interval and timer with a period, fromEvent and fromEventPattern, any Subject or BehaviorSubject, webSocket, from over an async iterator, and any observable that another part of the system keeps feeding. If the source’s subscribe function does not call subscriber.complete() on its own, the subscription is indefinite by default.

There is a second, quieter leak shape that does not involve forgetting to unsubscribe: the inner subscription. Operators like mergeMap create a subscription for every value they receive, and each one is an independent lifetime that the outer unsubscribe does not necessarily reach. The outer subscription is torn down correctly, the outer observable releases everything it holds, and the inners keep running because they were never part of the outer chain โ€” they were started by an operator and are only stopped when that operator decides to stop them.

import { fromEvent, interval, mergeMap } from "rxjs";

// Every click starts a new interval. mergeMap holds all of them open at
// once, and none of them completes, so the count grows without bound.
fromEvent(document, "click")
  .pipe(mergeMap(() => interval(1000)))
  .subscribe((n) => console.log(n));
// After 50 clicks there are 50 independent intervals running.

The third shape is retention rather than subscription: an operator that deliberately keeps a connection open to serve a cache. shareReplay with refCount: false holds the source subscription for as long as the shared observable exists, regardless of how many downstream subscribers come and go. That is the correct behaviour for a cache that must stay warm, and it is a leak whenever it was chosen without that intent.


b. takeUntil: the completion notifier

takeUntil is the general answer to “this stream must stop when that event happens.” You give it a notifier observable; when the notifier emits its first value, takeUntil completes the source it is applied to, and the completion travels downstream to the final subscriber, which closes its Subscription and runs every teardown in the chain. It is not an unsubscribe โ€” it is a completion โ€” and that distinction matters because complete handlers fire along the way.

import { Subject, interval, takeUntil } from "rxjs";

// The notifier is a Subject because we need to push into it from outside
// the stream. It is long-lived and shared by every stream in the group.
const destroy$ = new Subject<void>();

interval(1000)
  .pipe(
    // When destroy$ emits, takeUntil completes the source. The completion
    // propagates to the subscriber, which then detaches from `interval`
    // and clears the underlying timer.
    takeUntil(destroy$)
  )
  .subscribe({
    next: (n) => console.log(n),
    complete: () => console.log("stopped by notifier"),
  });

// Later, at teardown time: emit once to trigger every takeUntil, then
// complete the Subject so it does not itself stay subscribed by anything.
destroy$.next();
destroy$.complete();

Two failure modes come from misusing the notifier rather than the operator. The first is a notifier that completes without ever emitting: takeUntil subscribes to the notifier, sees only a complete, and concludes that the “stop” signal will never arrive. The source runs forever. The second is a notifier that is created per subscription rather than shared โ€” a fresh Subject per subscribe will never be emitted into by the code that holds the other reference.

import { EMPTY, interval, takeUntil } from "rxjs";

// โŒ EMPTY completes without emitting, so takeUntil never fires and the
//    interval is never stopped. The pipe looks correct and does nothing.
interval(1000).pipe(takeUntil(EMPTY)).subscribe();

// โœ… A Subject that is emitted into and then completed is the correct
//    shape: emission stops the stream, completion releases the notifier.
const destroy$ = new Subject<void>();
interval(1000).pipe(takeUntil(destroy$)).subscribe();
destroy$.next();

Position within the pipe is the other rule. takeUntil completes the observable directly upstream of it, and everything downstream receives a complete notification. That is normally fine โ€” but an operator placed after takeUntil that responds to completion by resubscribing will resurrect the source, and by then the notifier has already fired and cannot stop it again.

// โœ… takeUntil last: it completes the entire chain above it and the
//    subscriber detaches. Nothing below it can restart the source.
source$
  .pipe(
    switchMap((id) => get(`/api/items/${id}`)), // inner request cancelled
    takeUntil(destroy$)
  )
  .subscribe(render);

// โŒ takeUntil before repeat(): the completion triggers a resubscribe of
//    everything above, including a takeUntil whose notifier has already
//    fired. The chain restarts and runs forever.
source$
  .pipe(
    takeUntil(destroy$),
    repeat() // sees `complete`, resubscribes, and loops
  )
  .subscribe(render);

For the degenerate case where the stream should produce exactly one value, take(1) is smaller and more direct than a notifier. It completes the source after the first emission, which closes the Subscription automatically, and no lifecycle object needs to exist at all.

import { take } from "rxjs";

// take(1) completes the source after one value. The Subscription closes
// itself, so there is nothing to unsubscribe and nothing to remember.
config$.pipe(take(1)).subscribe((cfg) => apply(cfg));

// `first()` is the same with an error on empty; `take(1)` is silent.

c. Subscription composition โ€” add, remove, and the cascade

When a unit of work owns several streams, the cleanest lifetime is a single Subscription that contains them all. Subscription is a container: add() attaches a child teardown, and unsubscribe() on the parent cascades to every child in insertion order. The parent holds no data of its own, which is exactly why it works as an owner โ€” it exists only to be torn down.

import { Subscription, interval } from "rxjs";

// The root subscription contains no stream. It is a teardown container.
const root = new Subscription();

// `add` returns void in RxJS 7, so these calls cannot be chained. Each
// child is a Subscription produced by subscribe().
root.add(interval(1000).subscribe((n) => console.log("a", n)));
root.add(interval(500).subscribe((n) => console.log("b", n)));

// One call cascades to both children, in the order they were added.
root.unsubscribe();

// After the cascade the root is closed and cannot be reused.
console.log(root.closed); // true

The closed flag is the detail that makes the pattern safe. Adding a teardown to an already-closed Subscription runs that teardown immediately rather than silently accepting it. That means an asynchronous code path which subscribes after the container was destroyed cannot create a new leak โ€” the subscription is closed on arrival.

import { Subscription, timer } from "rxjs";

const root = new Subscription();
root.unsubscribe(); // the owner is already gone

// โŒ-proof: `add` on a closed Subscription executes the teardown at once,
// so a late asynchronous subscribe cannot outlive its owner.
root.add(timer(5000).subscribe(() => console.log("late")));
// The timer is created and unsubscribed in the same tick.

remove() detaches a child without unsubscribing it. That is the tool for a stream that should move to a different owner, not the tool for stopping one โ€” removing a child and then forgetting about it turns one leak into another.

import { Subscription, interval } from "rxjs";

const root = new Subscription();
const child = interval(1000).subscribe();

root.add(child);      // child is now owned by root
root.remove(child);   // detached, but still running
child.unsubscribe();  // the actual stop โ€” remove() did not do this

// The common composite form: one owner per unit of work, and every
// stream in that unit registered against it at creation time.
const viewSub = new Subscription()
  .add(click$.subscribe(handleClick))
  .add(resize$.subscribe(handleResize))
  .add(visibility$.subscribe(handleVisibility));
// A single call to viewSub.unsubscribe() ends all three.

merge is the alternative when the streams are homogeneous and can share an error path: it multiplexes several observables into one, so one subscription and one unsubscribe covers all of them. The trade-off is that an error from any one stream errors the merged observable and tears down the others, which is often not what you want for unrelated streams.

import { merge } from "rxjs";

// โœ… One subscription for many streams, when they share a handler and
//    can share a fate. An error in either one ends both.
const merged = merge(a$, b$, c$).subscribe(handle);
merged.unsubscribe();

// โœ… A Subscription container is better when the streams are unrelated
//    and must fail independently.
const root = new Subscription();
root.add(a$.subscribe(handleA));
root.add(b$.subscribe(handleB));
root.unsubscribe();

finalize closes the gap between subscription lifetime and resource lifetime. It runs on complete, on error, and on unsubscribe alike, which makes it the single correct place to release something that unsubscribe alone does not reach.

import { finalize } from "rxjs";

socket$
  .pipe(
    // Runs on complete, error and unsubscribe โ€” the only hook that covers
    // all three, and therefore the only safe place to close the resource.
    finalize(() => socket.close())
  )
  .subscribe(handleMessage);

d. AbortSignal โ€” cancellation that crosses the boundary

Everything so far lives inside RxJS. The platform speaks a different language: fetch takes an AbortSignal, addEventListener accepts one in its options object, and Promise-based APIs generally accept one too. AbortSignal is the web standard for cancellation, and the two bridges between it and RxJS are the subject of this section.

The first bridge turns a signal into an observable. AbortSignal is an EventTarget, it dispatches an "abort" event exactly once, and fromEvent accepts any EventTarget. That gives a notifier observable, which combines with takeUntil into a complete cancellation chain.

import { fromEvent, takeUntil } from "rxjs";

const controller = new AbortController();

// Bridge 1: an AbortSignal is an EventTarget that dispatches "abort" once.
// fromEvent turns it into a notifier observable.
const aborted$ = fromEvent(controller.signal, "abort").pipe(take(1));

longRunning$
  .pipe(
    // When the signal aborts, the chain completes and every teardown in it
    // runs. This is the completion route, not the error route.
    takeUntil(aborted$)
  )
  .subscribe(handleValue);

// Anywhere else in the program, on teardown:
controller.abort();

The second bridge goes the other way: it takes a signal and makes the observable obey it. RxJS provides this as the abortable operator, which subscribes to the source, watches the signal, and on abort does two things โ€” it unsubscribes the source and it errors the downstream subscriber with a DOMException named AbortError. It is deliberately an error rather than a completion, because an abort is an outcome, not a natural ending, and the distinction lets catchError handle it separately.

import { abortable, interval } from "rxjs";

const controller = new AbortController();

interval(1000)
  .pipe(
    // Bridge 2: the signal drives the operator. On abort the source is
    // unsubscribed and the chain errors with a DOMException "AbortError".
    abortable(controller.signal)
  )
  .subscribe({
    next: (n) => console.log(n),
    error: (err) => {
      // Filter the abort out of the error path; rethrow anything else.
      if (err.name !== "AbortError") throw err;
    },
  });

// If the signal is already aborted when `abortable` subscribes, the
// observable errors immediately without touching the source at all.
controller.abort();

fromFetch combines both bridges internally, which is why it is the recommended way to do HTTP in RxJS. It passes your signal through to the underlying fetch, and it also creates its own internal AbortController that it aborts when the subscriber unsubscribes. The result is that unsubscribing from the observable cancels the request at the network level, and the connection is not merely orphaned.

import { fromFetch } from "rxjs/fetch";
import { switchMap } from "rxjs";

const controller = new AbortController();

fromFetch("/api/users", {
  // The signal is forwarded to fetch, and fromFetch also aborts the
  // request internally when the subscriber unsubscribes.
  signal: controller.signal,
})
  .pipe(
    // switchMap owns the response body stream and cancels it on a new value.
    switchMap((res) => res.json())
  )
  .subscribe({ next: (users) => render(users) });

// Cancels the in-flight request at the network layer, not just the observer.
controller.abort();

A signal can come from outside your code, and it carries a reason. controller.abort(reason) stores any value on signal.reason, which the AbortError surfaces โ€” so a cancelled request can be distinguished from a failed one without inventing a sentinel. AbortSignal.timeout(ms) produces a signal that aborts itself, which is the shortest correct implementation of a request timeout.

// A timeout is a signal that aborts itself. No timer, no manual abort call.
const timed = AbortSignal.timeout(5000);
fromFetch("/api/slow", { signal: timed }).subscribe({ error: handle });

// A custom reason travels on the signal and reaches the error handler.
const controller = new AbortController();
controller.abort(new Error("user navigated away"));
console.log(controller.signal.reason); // Error: user navigated away

e. Operator-level ownership โ€” where you should not write teardown

Some operators already own their inner subscriptions completely, and adding lifecycle code around them is not just redundant, it hides the real question. switchMap is the clearest case: it subscribes to exactly one inner observable at a time and unsubscribes it the moment the outer source emits again. That is cancellation, built into the operator, with no notifier and no Subscription required.

import { switchMap, debounceTime } from "rxjs";

// switchMap maintains one inner subscription. Every new outer value
// unsubscribes the previous inner before subscribing the next one.
searchInput$
  .pipe(
    debounceTime(300),              // also owns its timer and clears it
    switchMap((term) => search(term)) // the previous request is cancelled
  )
  .subscribe(renderResults);
// Typing quickly produces one live request, not one per keystroke.

mergeMap is the opposite: it subscribes to every inner observable and keeps them all alive until each completes on its own. With a finite inner (an HTTP call that completes) that is fine. With a non-completing inner it is an unbounded leak, and the shape of the bug โ€” one mergeMap over a stream of clicks โ€” is common enough that it is worth recognising on sight.

import { mergeMap, switchMap, exhaustMap } from "rxjs";

// โŒ Every click adds a permanent interval. Nothing cancels the previous.
clicks$.pipe(mergeMap(() => interval(1000))).subscribe();

// โœ… switchMap: one inner at a time, previous cancelled.
clicks$.pipe(switchMap(() => interval(1000))).subscribe();

// โœ… exhaustMap: ignore new outer values while an inner is still running.
clicks$.pipe(exhaustMap(() => saveRequest())).subscribe();

shareReplay is the retention case. Its purpose is to keep a source subscription alive so that late subscribers see the last value without re-triggering the source, and refCount: false means it does so even when there are no subscribers at all. That is a correct cache and an incorrect default; refCount: true ties the source subscription to the subscriber count and releases it when the last one leaves.

import { shareReplay, share } from "rxjs";

// โŒ refCount:false keeps the source subscription open forever. The cache
//    stays warm, and the source's resources are never released.
const alwaysOn$ = source$.pipe(shareReplay({ bufferSize: 1, refCount: false }));

// โœ… refCount:true releases the source when the last subscriber leaves.
const bounded$ = source$.pipe(shareReplay({ bufferSize: 1, refCount: true }));

// โœ… share() with resetOnRefCountZero gives the same behaviour without
//    replaying a value to new subscribers.
const shared$ = source$.pipe(share({ resetOnRefCountZero: true }));

The remaining operators that hold state โ€” debounceTime, throttleTime, auditTime, delay โ€” all clear their internal timers when they are unsubscribed, so they are only a leak if the chain around them is. retry and repeat do the opposite: they resubscribe the source, which means a source that keeps failing will keep retrying until a take or a takeUntil is placed downstream of them.

import { retry, take, timer } from "rxjs";

// โŒ Unbounded retry: resubscribes forever, and each attempt is a new
//    connection that is not released until the chain ends โ€” which is never.
request$.pipe(retry()).subscribe();

// โœ… Bounded retry, and takeUntil-below or take-above to end the chain.
request$.pipe(retry({ count: 3 }), take(1)).subscribe();

Complete Example Session

// ============================================
// PART 1: THE LEAK โ€” AN INDEFINITE SUBSCRIBE
// ============================================
import { interval, fromEvent, Subject, Subscription, merge } from "rxjs";
import { takeUntil, take, finalize, switchMap, mergeMap, shareReplay, abortable } from "rxjs";
import { fromFetch } from "rxjs/fetch";

// `interval` never completes, so this Subscription would live forever and
// keep the callback (and its closure) reachable for the life of the page.
const alwaysOn = interval(1000).subscribe((n) => console.log("tick", n));

// ============================================
// PART 2: THE FIX โ€” A takeUntil NOTIFIER
// ============================================
const destroy$ = new Subject<void>(); // the lifecycle notifier

interval(1000)
  .pipe(
    // Completes the source when destroy$ emits, which closes the
    // final Subscription and clears the underlying timer.
    takeUntil(destroy$)
  )
  .subscribe({
    next: (n) => console.log("bounded tick", n),
    complete: () => console.log("stream completed by notifier"),
  });

// ============================================
// PART 3: ENDING THE NOTIFIER CORRECTLY
// ============================================
// Emit once to trigger every takeUntil using this notifier...
destroy$.next();
// ...then complete it so the Subject itself holds no subscriptions.
destroy$.complete();

// ============================================
// PART 4: finalize โ€” THE RESOURCE HOOK
// ============================================
const socket = new WebSocket("wss://example.com/feed");

const socket$ = new Subject<string>();

socket.addEventListener("message", (e) => socket$.next(e.data));

const socketSub = socket$
  .pipe(
    // finalize runs on complete, error AND unsubscribe โ€” the only hook
    // that fires for all three, so resource closure belongs here.
    finalize(() => socket.close())
  )
  .subscribe((msg) => console.log(msg));

// Closing the subscription also closes the socket.
socketSub.unsubscribe();

// ============================================
// PART 5: SUBSCRIPTION COMPOSITION โ€” ONE OWNER
// ============================================
// The root subscribes to nothing itself; it is a teardown container.
const viewSub = new Subscription();

// Each child is registered at creation time, so nothing is forgotten.
viewSub.add(fromEvent(window, "resize").subscribe(() => layout()));
viewSub.add(fromEvent(window, "scroll").subscribe(() => track()));
viewSub.add(interval(5000).subscribe(() => poll()));

// A single call cascades to all three, in insertion order.
viewSub.unsubscribe();

// ============================================
// PART 6: THE CLOSED GUARD
// ============================================
const lateSub = new Subscription();
lateSub.unsubscribe(); // the owner is already gone

// Adding to a closed Subscription executes the teardown immediately,
// so an asynchronous subscribe cannot outlive its owner.
lateSub.add(interval(1000).subscribe(() => console.log("never runs")));

// ============================================
// PART 7: INNER OWNERSHIP โ€” switchMap vs mergeMap
// ============================================
const clicks$ = fromEvent(document, "click");

// โœ… switchMap owns one inner subscription and cancels it on the next click.
clicks$.pipe(switchMap(() => interval(1000))).subscribe();

// โŒ mergeMap owns every inner subscription and cancels none of them.
// clicks$.pipe(mergeMap(() => interval(1000))).subscribe();

// ============================================
// PART 8: SIGNAL โ†’ OBSERVABLE
// ============================================
const controller = new AbortController();

longRunning$
  .pipe(
    // An AbortSignal is an EventTarget that dispatches "abort" exactly once,
    // so fromEvent + takeUntil turns it into a cancellation notifier.
    takeUntil(fromEvent(controller.signal, "abort"))
  )
  .subscribe(handleValue);

// ============================================
// PART 9: OBSERVABLE โ†’ SIGNAL, AND fromFetch
// ============================================
interval(1000)
  .pipe(
    // `abortable` unsubscribes the source and errors with DOMException
    // "AbortError" when the signal fires.
    abortable(controller.signal)
  )
  .subscribe({ error: (err) => err.name === "AbortError" || console.error(err) });

fromFetch("/api/users", { signal: controller.signal })
  .pipe(switchMap((res) => res.json()))
  .subscribe({ next: (users) => render(users) });

// One abort cancels the interval and the in-flight HTTP request together.
controller.abort();

// ============================================
// PART 10: CACHES AND RETENTION
// ============================================
// โŒ refCount:false keeps the source subscription open with no subscribers.
const alwaysCached$ = source$.pipe(shareReplay({ bufferSize: 1, refCount: false }));

// โœ… refCount:true releases the source when the last subscriber leaves.
const bounded$ = source$.pipe(shareReplay({ bufferSize: 1, refCount: true }));

// โœ… take(1) closes the Subscription on its own โ€” no notifier needed.
config$.pipe(take(1)).subscribe((cfg) => apply(cfg));

The ten parts moved from the leak itself through each of the four cancellation mechanisms: the notifier, the notifier’s own lifecycle, the resource hook in finalize, the Subscription container with its closed guard, the operators that already own their inners, both directions of the AbortSignal bridge, and finally the retention cases where a subscription is meant to stay open.


Quick Reference

The Four Cancellation Tools

ToolWhat It EndsHow It Ends
takeUntil(notifier$)The chain above itCompletion
Subscription.unsubscribe()The container and all childrenTeardown cascade
AbortSignal / abortableThe source and platform resourceAbortError
switchMap / take(1)The inner or the sourceOperator-managed

takeUntil Rules

RuleReason
Place it last in the pipeNothing downstream can resubscribe the source
Use a shared SubjectA per-subscription notifier is never emitted into
Emit, then complete the notifierEmission stops streams, completion releases the Subject
Never pass EMPTYCompletion without emission never fires

Subscription API

MemberBehaviour
add(teardown)Attaches a child; returns void in RxJS 7
remove(teardown)Detaches without unsubscribing
unsubscribe()Cascades to all children, in order
closedtrue after unsubscribe; add then runs immediately
unsubscribe twiceSafe no-op

Leak-Prone Operators

OperatorRisk
mergeMapKeeps every inner subscription open
shareReplay({refCount:false})Keeps the source open with no subscribers
retry() / repeat()Resubscribes without a bound
SubjectHolds every subscriber until they unsubscribe

AbortSignal Surface

APIPurpose
new AbortController()Owns the signal and the abort() call
controller.signalThe read-only signal passed to APIs
controller.abort(reason)Fires once, stores signal.reason
AbortSignal.timeout(ms)A signal that aborts itself
fromEvent(signal, "abort")Signal โ†’ observable
abortable(signal)Signal โ†’ operator, errors with AbortError

Best Practices

โœ… Do This:

// Give every indefinite stream an explicit owner
interval(1000).pipe(takeUntil(destroy$)).subscribe();     // โœ…

// Keep takeUntil as the last operator in the pipe
source$.pipe(switchMap(fetchItem), takeUntil(destroy$));  // โœ…

// Aggregate related streams into one Subscription
const root = new Subscription().add(a$).add(b$);          // โœ…

// Release platform resources in finalize
socket$.pipe(finalize(() => socket.close()));             // โœ…

// Pass the signal through to fetch
fromFetch(url, { signal: controller.signal });            // โœ…

// Tie a replay cache to its subscriber count
source$.pipe(shareReplay({ bufferSize: 1, refCount: true })); // โœ…

โŒ Don’t Do This:

// Subscribe to an indefinite source and walk away
interval(1000).subscribe(render);                         // โŒ

// Put a resubscribing operator below takeUntil
source$.pipe(takeUntil(destroy$), repeat());              // โŒ

// Use a fresh Subject per subscription as the notifier
source$.pipe(takeUntil(new Subject<void>()));             // โŒ

// Rely on unsubscribe alone to close a socket or request
socket$.subscribe(handle);                                // โŒ

// Keep a cache warm without meaning to
source$.pipe(shareReplay({ refCount: false }));           // โŒ

// Use unbounded retry on a failing source
request$.pipe(retry());                                   // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Handler fires many timesEach mount subscribed again, none unsubscribedtakeUntil per lifecycle
takeUntil never firesNotifier completes without emittingEmit before complete()
Notifier does nothingA new Subject created per subscriptionShare one Subject
Chain restarts foreverrepeat/retry placed below takeUntilMove takeUntil last
Request survives teardownNo signal passed to fetchfromFetch or signal
Cache never releasesshareReplay({ refCount: false })refCount: true
Duplicate inner timersmergeMap over a non-completing innerswitchMap or exhaustMap
Teardown does not runCleanup in complete instead of finalizeUse finalize

Real-World Examples

1. Page-scoped destroy notifier

const destroy$ = new Subject<void>();
interval(1000).pipe(takeUntil(destroy$)).subscribe(render);
destroy$.next(); destroy$.complete();

2. Notifier from a DOM signal

const controller = new AbortController();
stream$.pipe(takeUntil(fromEvent(controller.signal, "abort"))).subscribe();

3. One container per view

const viewSub = new Subscription().add(a$.subscribe(h)).add(b$.subscribe(g));
viewSub.unsubscribe();

4. Releasing a socket in finalize

socket$.pipe(finalize(() => socket.close())).subscribe(handle);

5. Cancelling the previous request

input$.pipe(switchMap((t) => fromFetch(`/api?q=${t}`))).subscribe();

6. Detecting a mergeMap leak

// One permanent interval per click โ€” unbounded growth
clicks$.pipe(mergeMap(() => interval(1000))).subscribe();

7. Aborting an observable with a signal

interval(1000).pipe(abortable(controller.signal)).subscribe({ error: ignoreAbort });

8. Wiring a signal into fetch

fromFetch("/api/data", { signal: controller.signal }).pipe(switchMap((r) => r.json()));

9. A self-expiring request timeout

fromFetch("/api/slow", { signal: AbortSignal.timeout(5000) });

10. Bounding a replay cache

state$.pipe(shareReplay({ bufferSize: 1, refCount: true }));

Visual

The Dangling Subscription

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  THE LEAK                                              โ”‚
โ”‚                                                        โ”‚
โ”‚  subscribe() โ”€โ”€โ–บ Subscriber โ”€โ”€โ–บ observer list          โ”‚
โ”‚                                                        โ”‚
โ”‚  interval(1000) emits forever                          โ”‚
โ”‚  nothing removes the entry unless you cancel           โ”‚
โ”‚                                                        โ”‚
โ”‚  unsubscribe() โ”€โ”€โ–บ entry removed                       โ”‚
โ”‚  complete      โ”€โ”€โ–บ entry removed                       โ”‚
โ”‚  neither       โ”€โ”€โ–บ entry stays                         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

takeUntil Completes the Chain

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  takeUntil: COMPLETION, NOT UNSUBSCRIBE                โ”‚
โ”‚                                                        โ”‚
โ”‚  notify$.next()                                        โ”‚
โ”‚        โ”‚                                               โ”‚
โ”‚        โ–ผ                                               โ”‚
โ”‚  source$ โ”€โ”€โ–บ takeUntil(notify$) โ”€โ”€โ–บ subscriber         โ”‚
โ”‚                     โ”‚                                  โ”‚
โ”‚                     โ””โ”€โ”€โ–บ source completes              โ”‚
โ”‚                        โ””โ”€โ”€โ–บ complete propagates        โ”‚
โ”‚                             โ””โ”€โ”€โ–บ Subscription closed   โ”‚
โ”‚                                  โ””โ”€โ”€โ–บ teardowns run    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Subscription Container

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  THE SUBSCRIPTION TREE                                 โ”‚
โ”‚                                                        โ”‚
โ”‚  root = new Subscription()                             โ”‚
โ”‚    โ”œโ”€โ”€ add(a$.subscribe())   โ†’ teardown A              โ”‚
โ”‚    โ”œโ”€โ”€ add(b$.subscribe())   โ†’ teardown B              โ”‚
โ”‚    โ””โ”€โ”€ add(c$.subscribe())   โ†’ teardown C              โ”‚
โ”‚                                                        โ”‚
โ”‚  root.unsubscribe()                                    โ”‚
โ”‚    โ””โ”€โ”€โ–บ A, B, C torn down                              โ”‚
โ”‚                                                        โ”‚
โ”‚  root.closed === true                                  โ”‚
โ”‚    โ””โ”€โ”€โ–บ add() runs immediately after this              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Two AbortSignal Bridges

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  TWO BRIDGES                                           โ”‚
โ”‚                                                        โ”‚
โ”‚  SIGNAL โ†’ OBSERVABLE                                   โ”‚
โ”‚  signal โ”€โ”€โ–บ fromEvent(signal, 'abort') โ”€โ”€โ–บ takeUntil   โ”‚
โ”‚                                                        โ”‚
โ”‚  OBSERVABLE โ†’ SIGNAL                                   โ”‚
โ”‚  signal โ”€โ”€โ–บ abortable(signal) โ”€โ”€โ–บ source$              โ”‚
โ”‚  controller.abort() โ”€โ”€โ–บ unsubscribe + AbortError       โ”‚
โ”‚                                                        โ”‚
โ”‚  fromFetch(url, { signal }) wires both ends for you    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
What leaksThe Subscriber and the closure it holds
Default lifetimeUntil unsubscribe or source completion
General notifiertakeUntil(notifier$)
Notifier shapeA shared Subject<void>
Notifier positionLast operator in the pipe
ContainerSubscription with add() children
Resource hookfinalize() โ€” complete, error, unsubscribe
Signal โ†’ streamfromEvent(signal, "abort")
Signal โ†’ operatorabortable(signal), errors with AbortError
HTTP with cancellationfromFetch(url, { signal })
Retention riskshareReplay({ refCount: false })

Key takeaways:

  • The leak is the Subscriber, not the observable. A subscription registers a callback with a source and holds everything that callback closes over. An indefinite source never empties that list on its own, and nothing warns you when it grows.
  • takeUntil is a completion, not an unsubscribe. The notifier emits, the source completes, the completion propagates downstream, and the final Subscription closes. Complete handlers run along the way, which is why placement matters.
  • takeUntil belongs last in the pipe. Anything below it receives a complete, and a resubscribing operator below it โ€” repeat, retry โ€” will restart the source after the notifier has already fired and can no longer stop it.
  • A Subscription container is the right owner for a group. add() children, unsubscribe() once, and the cascade tears everything down in order. The closed flag makes a late asynchronous add() safe rather than a new leak.
  • finalize is the only hook that covers all three endings. Resource cleanup belongs there, because unsubscribe alone does not close a socket, a request, or a listener that the observable did not wire up.
  • AbortSignal is how cancellation leaves RxJS. fromEvent(signal, "abort") with takeUntil brings the signal in; abortable(signal) and fromFetch(url, { signal }) push it out. Aborting errors with AbortError so the abort path stays distinguishable from the failure path.
  • Some operators already own their inners. switchMap cancels the previous inner, exhaustMap ignores new ones, and take(1) completes the source. Writing teardown around them is redundant and obscures where the lifetime actually comes from.

Remember: Every subscription to an indefinite source is a process you started, and RxJS will not stop it for you. Decide the owner of that lifetime at the moment you write the subscribe() call โ€” a takeUntil notifier for a stream that dies with its view, a Subscription container for a group that dies together, or an AbortSignal when the work extends past RxJS into a network request or a DOM listener. Put takeUntil last, put resource cleanup in finalize, prefer the operator that already cancels (switchMap, take(1)) over hand-written teardown, and treat any cache with refCount: false as a deliberate decision rather than a default.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!