RxJS 12 ๐ฃ Memory Leaks & Cancellation โ Managing lifecycles with takeUntil, Subscription composition, and AbortSignal
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
| Tool | What It Ends | How It Ends |
|---|---|---|
takeUntil(notifier$) | The chain above it | Completion |
Subscription.unsubscribe() | The container and all children | Teardown cascade |
AbortSignal / abortable | The source and platform resource | AbortError |
switchMap / take(1) | The inner or the source | Operator-managed |
takeUntil Rules
| Rule | Reason |
|---|---|
| Place it last in the pipe | Nothing downstream can resubscribe the source |
Use a shared Subject | A per-subscription notifier is never emitted into |
| Emit, then complete the notifier | Emission stops streams, completion releases the Subject |
Never pass EMPTY | Completion without emission never fires |
Subscription API
| Member | Behaviour |
|---|---|
add(teardown) | Attaches a child; returns void in RxJS 7 |
remove(teardown) | Detaches without unsubscribing |
unsubscribe() | Cascades to all children, in order |
closed | true after unsubscribe; add then runs immediately |
unsubscribe twice | Safe no-op |
Leak-Prone Operators
| Operator | Risk |
|---|---|
mergeMap | Keeps every inner subscription open |
shareReplay({refCount:false}) | Keeps the source open with no subscribers |
retry() / repeat() | Resubscribes without a bound |
Subject | Holds every subscriber until they unsubscribe |
AbortSignal Surface
| API | Purpose |
|---|---|
new AbortController() | Owns the signal and the abort() call |
controller.signal | The 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Handler fires many times | Each mount subscribed again, none unsubscribed | takeUntil per lifecycle |
takeUntil never fires | Notifier completes without emitting | Emit before complete() |
| Notifier does nothing | A new Subject created per subscription | Share one Subject |
| Chain restarts forever | repeat/retry placed below takeUntil | Move takeUntil last |
| Request survives teardown | No signal passed to fetch | fromFetch or signal |
| Cache never releases | shareReplay({ refCount: false }) | refCount: true |
| Duplicate inner timers | mergeMap over a non-completing inner | switchMap or exhaustMap |
| Teardown does not run | Cleanup in complete instead of finalize | Use 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
| Item | Value |
|---|---|
| What leaks | The Subscriber and the closure it holds |
| Default lifetime | Until unsubscribe or source completion |
| General notifier | takeUntil(notifier$) |
| Notifier shape | A shared Subject<void> |
| Notifier position | Last operator in the pipe |
| Container | Subscription with add() children |
| Resource hook | finalize() โ complete, error, unsubscribe |
| Signal โ stream | fromEvent(signal, "abort") |
| Signal โ operator | abortable(signal), errors with AbortError |
| HTTP with cancellation | fromFetch(url, { signal }) |
| Retention risk | shareReplay({ 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.
takeUntilis 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.takeUntilbelongs last in the pipe. Anything below it receives acomplete, 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
Subscriptioncontainer is the right owner for a group.add()children,unsubscribe()once, and the cascade tears everything down in order. Theclosedflag makes a late asynchronousadd()safe rather than a new leak. finalizeis the only hook that covers all three endings. Resource cleanup belongs there, becauseunsubscribealone does not close a socket, a request, or a listener that the observable did not wire up.AbortSignalis how cancellation leaves RxJS.fromEvent(signal, "abort")withtakeUntilbrings the signal in;abortable(signal)andfromFetch(url, { signal })push it out. Aborting errors withAbortErrorso the abort path stays distinguishable from the failure path.- Some operators already own their inners.
switchMapcancels the previous inner,exhaustMapignores new ones, andtake(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.
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!