Sub topic 6
Automatic unsubscription and manualCleanup
This chapter assumes you can write Angular components, use inject(), create signals, and subscribe to RxJS observables. You should also know why toSignal needs an injection context, which an earlier chapter covered. Here you will see how toSignal ends its subscription, when you should take that job over yourself, and what goes wrong in each case.
What toSignal subscribes to, and when it stops
toSignal subscribes to the source observable immediately, at the moment you call it. It does not wait for the first read of the signal. This is different from the async pipe, which subscribes when the template renders.
Because the call happens in an injection context, toSignal can register a cleanup with the current DestroyRef. When that context is destroyed, the subscription is unsubscribed. For a component, this means the component is destroyed. For a root service, it means the application is destroyed.
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-ticker',
template: `<p>Seconds: {{ seconds() }}</p>`,
})
export class Ticker {
// Subscribed when Ticker is constructed, unsubscribed when Ticker is destroyed.
seconds = toSignal(interval(1000), { initialValue: 0 });
}You do not write ngOnDestroy, takeUntil, or unsubscribe(). The interval timer stops when the component leaves the page.
The lifetime follows the injector
The subscription lives as long as the injection context it was created in. That has two consequences.
- In a component field initializer or constructor, the lifetime is the component's.
- With the
injectoroption, the lifetime is that injector's. If you pass a root injector from a component, the subscription outlives the component.
import { Injector, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable } from 'rxjs';
export class Loader {
private injector = inject(Injector);
start(source$: Observable<string>) {
// The subscription ends when this injector is destroyed.
return toSignal(source$, { injector: this.injector });
}
}If Loader is provided in root, this.injector is the root injector. Every call to start() then creates a subscription that lasts until the whole application is destroyed. Calling start() repeatedly leaks one subscription per call.
Setting up the cleanup
When to use manualCleanup
Sometimes you want the subscription to continue after the context is destroyed. The manualCleanup option turns off the DestroyRef registration.
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable } from 'rxjs';
export function longLived(source$: Observable<number>) {
// Not tied to a DestroyRef. Ends only when source$ completes or errors.
return toSignal(source$, { initialValue: 0, manualCleanup: true });
}With manualCleanup: true, toSignal does not need an injection context for cleanup, because it never asks for a DestroyRef. The subscription ends only when the observable completes or errors. If the source never finishes, such as interval, the subscription runs for the life of the page.
Use manualCleanup when the observable is guaranteed to complete on its own, for example a single HTTP request, or when you need the signal to outlive its creator. In every other case, leave it off.
Summary of the options
| Situation | Setting | Subscription ends |
|---|---|---|
| Field initializer in a component | Default | When the component is destroyed |
| Method call with `injector` option | `injector` | When that injector is destroyed |
| Source completes by itself | `manualCleanup: true` | When the source completes |
| Source never completes | `manualCleanup: true` | Never, until page unload |
Common mistakes
- Creating
toSignalinsidengOnInitor an event handler without an injector. This fails because there is no injection context. - Passing a root injector from a short-lived component, so subscriptions pile up.
- Using
manualCleanupon aninterval, afromEvent, or a WebSocket stream, and never stopping it. - Assuming the subscription is lazy. It starts when
toSignalis called, even if no template reads the signal.
Exercise
A service provided in root has a method watch(id) that calls toSignal(this.http.get(...), { injector: this.injector }) with the root injector. It is called every time the user clicks a row. What is the problem, and how would you change the design?
Show answer
Each click creates a new subscription that lives until the application is destroyed, so subscriptions and signals accumulate. Create one signal from a stream that is driven by a source signal or Subject holding the selected id, for example toSignal(toObservable(this.id).pipe(switchMap(...))), and set the id on each click. The subscription is created once, and switchMap cancels the previous request.
Exercise
You call toSignal(interval(1000), { initialValue: 0, manualCleanup: true }) inside a component. The user navigates away. Does the timer keep running?
Show answer
Yes. manualCleanup stops toSignal from registering with the component's DestroyRef, and interval never completes, so nothing unsubscribes. Remove manualCleanup to get automatic cleanup.