Sub topic 11
Bridging signals and RxJS
This chapter assumes you know how signal(), computed() and effect() work, including injection contexts and cleanup. It also assumes basic RxJS: observables, subscribe, pipe, and operators such as switchMap. By the end you will be able to move values between signals and observables and know where each tool fits.
Why bridge the two worlds
Signals and observables solve different problems.
- A signal always holds a current value. You can read it synchronously at any time, and Angular tracks who read it.
- An observable is a stream of values over time. It may have no value yet, may emit many values, may fail, and may complete.
Many Angular APIs still return observables, such as HttpClient, the router's paramMap, and form valueChanges. Your templates and computed() values work with signals. Signals are good at holding state. RxJS is good at time-based work such as debouncing, cancelling stale requests, retrying, and combining streams.
The bridge lives in a separate entry point:
import { toSignal, toObservable } from '@angular/core/rxjs-interop';The two functions mirror each other.
| Row | `toSignal` | `toObservable` |
|---|---|---|
| Direction | Observable to signal | Signal to observable |
| Result | Read-only `Signal<T>` | `Observable<T>` |
| Subscription | Subscribes immediately | Subscribes to the signal through an internal effect |
| Needs injection context | Yes, or an `injector` option | Yes, or an `injector` option |
| Cleanup | Unsubscribes when the context is destroyed | Stops watching the signal when the context is destroyed |
From observable to signal with toSignal()
toSignal() subscribes to an observable and stores its latest emission in a signal.
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 TickerComponent {
seconds = toSignal(interval(1000), { initialValue: 0 });
}The field initializer runs in the component's injection context, so the call is allowed. When the component is destroyed, toSignal() unsubscribes for you. There is no ngOnDestroy and no takeUntilDestroyed.
The initial value problem
A signal must always have a value, but an observable might not have emitted yet. toSignal() handles this in three ways.
- No option. The signal type is
T | undefined, and it holdsundefineduntil the first emission. initialValue. The signal holds that value until the first emission, and its type staysT.requireSync: true. You promise the observable emits synchronously on subscribe, asBehaviorSubjectorof()does. The type staysTand no initial value is needed.
import { toSignal } from '@angular/core/rxjs-interop';
import { BehaviorSubject } from 'rxjs';
const theme$ = new BehaviorSubject<'light' | 'dark'>('light');
// Type is Signal<'light' | 'dark'>, with no undefined.
const theme = toSignal(theme$, { requireSync: true });If you set requireSync: true and the observable does not emit during subscription, toSignal() throws an error. Use it only for sources you know are synchronous.
Errors and completion
Completion is easy: when the observable completes, the signal keeps its last value.
Errors are less obvious. If the observable errors, the signal stores the error. The next time you read the signal, it throws that error. In a template this surfaces as an ordinary rendering error. Handle errors inside the pipeline, before toSignal():
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable, catchError, of } from 'rxjs';
declare const users$: Observable<string[]>;
const users = toSignal(
users$.pipe(catchError(() => of([] as string[]))),
{ initialValue: [] as string[] }
);A fallback value hides the failure from the UI. If the user needs to know something went wrong, emit an object such as { status: 'error' } instead of an empty list.
Subscription rules
- Use it once, not repeatedly.
toSignal()creates a subscription each time you call it. Calling it insidecomputed()oreffect()would create a new subscription on every run. Create the signal once as a field and read it in the reactive code. - Cold observables start work immediately. An
HttpClientcall wrapped intoSignal()sends its request as soon as the signal is created, whether or not anything reads it. Signals are lazy forcomputed(), buttoSignal()is eager. - Outside an injection context, pass an injector. In a method or a callback, use the
injectoroption. - Manual cleanup.
manualCleanup: truedisables the automatic unsubscribe. Use it only for observables that complete on their own, such as a single HTTP request.
import { Component, Injector, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { timer } from 'rxjs';
@Component({ selector: 'app-late', template: `{{ late() }}` })
export class LateComponent {
private injector = inject(Injector);
late = (() => undefined) as () => number | undefined;
start() {
this.late = toSignal(timer(1000), { injector: this.injector });
}
}This is legal, but reassigning a signal field is awkward. Prefer a field created at construction time. The example shows only how injector lets the call run outside the constructor.
From signal to observable with toObservable()
toObservable() turns a signal into an observable that emits whenever the signal's value changes.
import { Component, signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-burst',
template: `<button (click)="burst()">Burst</button>`,
})
export class BurstComponent {
count = signal(0);
constructor() {
toObservable(this.count).subscribe((value) => console.log('emitted', value));
}
burst() {
this.count.set(1);
this.count.set(2);
this.count.set(3);
}
}Two things stand out when you run this.
- After the first change detection pass it logs
emitted 0. The observable emits the signal's current value to each new subscriber. - Clicking the button logs only
emitted 3. It does not log 1 or 2.
Why intermediate values are lost
toObservable() is built on an effect(). Effects run later, during Angular's change detection, not at the moment you call set(). By the time the effect runs, the signal holds 3, so the observable sees one change.
This matches the effect behavior you saw earlier in this tutorial. It has practical consequences:
- Emissions are asynchronous. Code right after
count.set(3)cannot assume the observable has already emitted. - Intermediate values are skipped. If every value matters, such as a log of user actions, a signal is the wrong source. Use a
Subject. - Equal values are skipped. The signal's equality check applies first, so setting a signal to the same value triggers nothing.
A worked example: debounced search
The most common reason to bridge is to put RxJS operators between two pieces of signal state. A search box is the classic case. The query is state, so it is a signal. Debouncing and cancelling stale requests are stream work, so they use RxJS. The result is state again, so it returns to a signal.
import { Component, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, delay, distinctUntilChanged, of, switchMap } from 'rxjs';
function searchApi(term: string) {
return of([`${term} one`, `${term} two`]).pipe(delay(300));
}
@Component({
selector: 'app-search-box',
template: `
<input [value]="query()" (input)="onInput($event)" />
<ul>
@for (item of results(); track item) {
<li>{{ item }}</li>
}
</ul>
`,
})
export class SearchBoxComponent {
query = signal('');
results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((term) => searchApi(term))
),
{ initialValue: [] as string[] }
);
onInput(event: Event) {
this.query.set((event.target as HTMLInputElement).value);
}
}Follow the flow:
- The user types, and
onInputsetsquery. toObservable(this.query)emits the settled value after change detection.debounceTimewaits for 300 ms of quiet, anddistinctUntilChangeddrops repeats.switchMapcancels any search still running and starts a new one.toSignalstores the latest result, and the template re-renders.
The field order matters. query is declared before results, so it exists when results initializes. Both initializers run in the injection context.
Combining with computed
The signal returned by toSignal() is an ordinary read-only signal, so it works inside computed():
import { Component, computed } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { of } from 'rxjs';
@Component({
selector: 'app-summary',
template: `<p>{{ summary() }}</p>`,
})
export class SummaryComponent {
items = toSignal(of(['a', 'b', 'c']), { initialValue: [] as string[] });
summary = computed(() => `${this.items().length} items`);
}This is the preferred pattern. Convert at the edge, then derive with computed(). Do not subscribe in an effect() and copy values into another signal. That is the "derived state in an effect" mistake from the earlier chapter on choosing between computed(), effect() and event handlers, now with a subscription attached.
Choosing between signals and RxJS
| Situation | Prefer |
|---|---|
| Holding the current value of UI state | Signal |
| Deriving one value from others | `computed()` |
| Debouncing, throttling, retrying | RxJS operators |
| Cancelling a stale request when input changes | `switchMap` |
| Reacting to every event, with none dropped | `Subject` or output |
| Consuming an API that returns an observable | `toSignal()` at the edge |
| Passing state into an API that wants an observable | `toObservable()` |
A good rule is to keep state in signals, keep time-based logic in RxJS, and cross the boundary as few times as possible. Each crossing adds one effect or one subscription and one scheduling delay.
Common mistakes
- Calling
toSignal()outside an injection context. You get an error about the missing context. Move the call into a field initializer or constructor, or passinjector. - Forgetting that
toSignal()can beundefined. WithoutinitialValueorrequireSync, templates andcomputed()must handleundefined. - Expecting synchronous emission from
toObservable(). It emits after change detection. Test it withTestBed.flushEffects()or by running a change detection pass. - Creating
toSignal()repeatedly. Calling it in a method that runs often leaks subscriptions until the context is destroyed. - Letting errors reach the template. Add
catchErrorbeforetoSignal(). - Round-tripping unnecessarily. Converting a signal to an observable and back for no operator gains nothing.
Summary
toSignal() subscribes eagerly, holds the latest value, needs an initial value or requireSync, throws stored errors on read, and cleans up with its injection context. toObservable() is effect-based, so it emits asynchronously, starts with the current value, and skips intermediate changes. Use the pair to put RxJS operators between signal-based state, and convert at the edges of your component.
Exercise
A component declares price = signal(1) and subscribes to toObservable(this.price) in its constructor. A click handler runs this.price.set(2); this.price.set(3); this.price.set(4);. Which values does the subscriber receive after the click, and why?
Show answer
Only 4. toObservable() is built on an effect, which runs during change detection, after the handler finishes. By then the signal holds 4, so the observable emits once. The values 2 and 3 are never seen. To receive every value, use a Subject.
Exercise
You write items = toSignal(this.http.get<string[]>('/api/items')) and the template runs items().length. What is wrong, and how do you fix it?
Show answer
Without initialValue or requireSync, the signal is undefined until the response arrives, so items().length fails (and TypeScript reports items() as possibly undefined). Pass { initialValue: [] }, or use items()?.length. Also add catchError before toSignal(), because a failed request would otherwise make the signal throw when read.
Exercise
Why is it wrong to call toSignal() inside a computed() callback?
Show answer
A computed callback re-runs whenever its dependencies change, so each run would create a new subscription that lives until the injection context is destroyed. Create the signal once as a field, then read it inside the computed().