Sub topic 6
Automatic unsubscription and manualCleanup
This chapter covers when toSignal subscribes to an observable, what ends that subscription, and when you should take over cleanup yourself. It assumes you can create a component with injected services and use signal() and computed(). It also assumes you know how subscribe, unsubscribe and operators such as take and takeUntil work in RxJS.
The subscription belongs to the signal
toSignal subscribes to the source observable immediately, at the moment you call it. It does not wait for a template or an effect to read the signal. The subscription then feeds each emitted value into an internal signal.
This has two consequences:
- A cold observable, such as an
HttpClientrequest, starts running as soon astoSignalis called, even if nothing ever reads the signal. - Every
toSignalcall creates its own subscription. Two calls on the same cold observable run the source twice.
Since the subscription starts without you asking, something has to end it. For an infinite source such as interval(1000), nothing inside the observable will. If the subscription outlived the component, the timer would keep running and keep updating a signal nobody reads. That is a memory and CPU leak.
How automatic unsubscription works
When you call toSignal in an injection context, it asks for a DestroyRef and registers the unsubscribe call as a destroy callback. A DestroyRef is an object that tells you when its owner, such as a component, directive or injector, is being destroyed. When the owner is destroyed, Angular runs the callback and the subscription ends.
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { finalize, interval } from 'rxjs';
@Component({
selector: 'app-clock',
template: `<p>Ticks: {{ ticks() }}</p>`,
})
export class Clock {
// The subscription is torn down when Clock is destroyed.
ticks = toSignal(
interval(1000).pipe(finalize(() => console.log('clock unsubscribed'))),
{ initialValue: 0 },
);
}The finalize operator runs when the subscription ends for any reason: completion, error or unsubscribe. Rendering <app-clock /> inside an @if block and toggling the condition off logs clock unsubscribed. You wrote no ngOnDestroy and no Subscription field.
The owner of the subscription is whatever DestroyRef is in scope where you call toSignal:
| Where you call `toSignal` | Which `DestroyRef` it uses | The subscription ends when |
|---|---|---|
| Field initializer or constructor of a component | The component's node injector | The component is destroyed |
| Field initializer or constructor of a directive | The directive's node injector | The host element is destroyed |
| Field initializer of a `providedIn: 'root'` service | The root environment injector | The application is destroyed |
| Field initializer of a service provided in a component's `providers` | That component's node injector | The component is destroyed |
| Any place, with the `injector` option | The injector you passed | That injector is destroyed |
The root service row matters. A signal created in a root service lives for the whole application, so its subscription does too. This is usually what you want for shared state, but it is permanent. Do not put a subscription to a per-page resource in a root service unless you accept that.
Where cleanup comes from when there is no injection context
The previous chapters showed that calling toSignal in a regular method fails with error NG0203, because no DestroyRef can be found. The injector option fixes this by naming the injector whose lifetime should own the subscription:
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>) {
// Ownership passes to the injector you supply.
return toSignal(source$, { injector: this.injector });
}
}Here the injector is the one that was current when Loader was created. If Loader is created by a component, the subscription ends with that component. If it is created by the root injector, the subscription lasts for the whole app.
You can only pass an injector that matches the lifetime you want. Passing the root injector from inside a component keeps the subscription alive after the component is gone.
Taking over with manualCleanup
Sometimes you do not want Angular to tie the subscription to a DestroyRef. Setting manualCleanup: true turns off the automatic unsubscription:
toSignal(source$, { manualCleanup: true });With this option:
toSignalno longer registers a destroy callback.- It no longer requires an injection context, because it no longer needs a
DestroyRef. - The subscription ends only when the source observable completes or errors.
The last point is the one to remember. toSignal returns a read-only signal, not a Subscription. You get no handle to call unsubscribe() on. If the source never completes, the subscription lives as long as the source object is reachable. That could be forever.
So manualCleanup is safe in two situations:
- The source completes by itself.
- You control the source and can complete it, for example with
takeUntil.
A finite source
An HttpClient call emits once and completes. Cleanup is not a concern, and manualCleanup lets you call toSignal from anywhere:
import { HttpClient } from '@angular/common/http';
import { toSignal } from '@angular/core/rxjs-interop';
export interface User {
id: number;
name: string;
}
export function loadUsers(http: HttpClient) {
// The request completes after one response, so nothing is left running.
return toSignal(http.get<User[]>('/api/users'), {
manualCleanup: true,
initialValue: [] as User[],
});
}loadUsers is a plain function. It needs no injection context, because no destroy callback is registered.
An infinite source with an explicit stop
When the source is infinite, you must complete it yourself. A Subject combined with takeUntil does this:
import { Signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Subject, interval, takeUntil } from 'rxjs';
export class Poller {
private stop$ = new Subject<void>();
readonly ticks: Signal<number> = toSignal(
interval(5000).pipe(takeUntil(this.stop$)),
{ manualCleanup: true, initialValue: 0 },
);
stop(): void {
this.stop$.next();
this.stop$.complete();
}
}Calling stop() makes takeUntil complete the stream, which ends the subscription. This lets you create a Poller anywhere, including in code that runs outside Angular's lifecycle. The cost is that you must remember to call stop(). Nothing will do it for you.
What the signal does after the subscription ends
The subscription can end in four ways:
- The owner is destroyed (automatic cleanup).
- The source completes.
- The source errors.
- You complete it through your own operator.
What the signal shows afterwards depends on which one happened:
| How the subscription ended | What reading the signal does |
|---|---|
| Owner destroyed | Returns the last value it held. It never updates again. |
| Source completed | Returns the last emitted value. |
| Source errored | Throws the error on every read. |
Reading a signal after its owner is destroyed does not throw. The value is just stale. This rarely matters for components, because the template is gone with them. It can matter for a service that outlives the thing it was created for. You may hold a signal whose source stopped without warning.
Errors are covered in the previous chapter. The point here is that an error also ends the subscription. So a signal that throws on read is also one that will never update again.
Deciding which lifetime you need
The choice is mostly about who should own the subscription:
In practice the default is correct in most code. Reach for the injector option when a method creates the signal later, for example in response to a click. Reach for manualCleanup when the source is finite or you already have a clear way to stop it.
toObservable and cleanup
toObservable works the other way, but its lifetime follows the same rule. It creates an internal effect that reads the signal, and that effect is tied to the DestroyRef of the injection context. When the owner is destroyed, the effect stops and the observable completes. Subscribers that used takeUntil-free subscribe calls then receive a complete notification.
The part you still own is your own subscriber. If you call .subscribe() on the result of toObservable, the observable completes when the owner is destroyed. But if you subscribe from somewhere with a shorter lifetime, you must unsubscribe yourself. The takeUntilDestroyed operator from the same package covers this, using a DestroyRef the same way toSignal does:
import { Component, DestroyRef, inject, signal } from '@angular/core';
import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-logger',
template: `<button (click)="n.update((v) => v + 1)">Add</button>`,
})
export class Logger {
n = signal(0);
private destroyRef = inject(DestroyRef);
start(): void {
// Called from a click handler, not from the constructor,
// so pass the DestroyRef explicitly.
toObservable(this.n, { injector: undefined })
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((v) => console.log('n =', v));
}
}Calling toObservable inside start() is an injection-context problem of its own. Outside a constructor or field initializer, you would also pass injector to toObservable. The example above passes undefined, which does not fix that. The reliable pattern is to create the observable once in a field initializer and call .subscribe later:
import { Component, DestroyRef, inject, signal } from '@angular/core';
import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-logger-fixed',
template: `<button (click)="n.update((v) => v + 1)">Add</button>`,
})
export class LoggerFixed {
n = signal(0);
private destroyRef = inject(DestroyRef);
private n$ = toObservable(this.n);
start(): void {
this.n$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((v) => console.log('n =', v));
}
}The field n$ is built in an injection context. start() can run later, from any event, and takeUntilDestroyed(this.destroyRef) ends the subscriber when the component is destroyed.
Common mistakes
- Wrapping
toSignalin acomputedoreffect. Each run would create a new subscription, and Angular reports an error because signal writes are not allowed in those contexts. Create the signal once, in a field initializer. - Calling
toSignalinngOnInitor an event handler. These run outside the injection context. Move the call to a field initializer, or passinjector. - Using
manualCleanupto silence the NG0203 error. The error goes away, but the subscription is now yours to end. If the source is infinite, you have traded a visible error for a silent leak. - Expecting reads to control the subscription. Reading or not reading the signal has no effect on whether the source runs.
- Creating
toSignalcalls on the same cold source in several places. Each creates a separate subscription and a separate HTTP request. Create one signal and share it, or useshareReplayon the source.
Exercise
A root-provided service has the field ticks = toSignal(interval(1000), { initialValue: 0 }). A component injects the service, displays ticks(), and is later destroyed. Does the interval keep running after the component is destroyed? Why?
Show answer
Yes. The service is provided in the root injector, so toSignal took the root DestroyRef. The subscription ends only when the application is destroyed. The component's destruction does not affect it.
Exercise
You write toSignal(source$, { manualCleanup: true }) in a method that runs on a button click, and source$ is interval(500). The code no longer throws NG0203. What is the remaining problem, and name two ways to fix it?
Show answer
The subscription is never cleaned up, because manualCleanup disables the DestroyRef callback and interval never completes. Fix it either by adding takeUntil(stop$) to the source and completing stop$ when you are done, or by removing manualCleanup and passing { injector } so the owning injector ends the subscription.