9. RxJS + Signals: When to Use Which and How to Migrate
Decision framework, interop patterns, and a practical migration playbook
Angular now has two reactivity systems: RxJS Observables and Signals. They solve different problems. Observables excel at asynchronous event streams — HTTP, WebSockets, route changes, complex coordination. Signals excel at synchronous state — component data, derived values, template bindings. This article gives you a clear framework for choosing between them, shows every interop pattern, and walks through migrating real code from one to the other.
The Decision Framework
Before reaching for either primitive, ask two questions:
- Is the value synchronous or asynchronous?
- Do I need stream operators (debounce, retry, combine, switchMap)?
The quick decision rule
| Scenario | Use | Why |
|---|---|---|
| Component-local state (counters, toggles, form fields) | Signal | Synchronous, always has a value, no cleanup needed |
| Derived / computed state | computed() | Memoized, lazy, glitch-free |
| HTTP requests | Observable (or resource()) | Async, may error, needs cancelation |
| WebSocket / SSE streams | Observable | Ongoing async stream, needs operators |
| Route parameters | Observable → toSignal() | Async source, but template wants synchronous read |
| Debounced search | Signal → toObservable() → RxJS → toSignal() | Need debounceTime + switchMap, then template binding |
| Form value changes | Observable (Reactive Forms) or Signal (template-driven) | Reactive Forms are Observable-native; simple forms are easier with Signals |
| Global app state (NgRx) | Observable + selectSignal() | NgRx store is Observable-based; selectSignal bridges to templates |
| Animation / rAF loops | Neither — use NgZone.runOutsideAngular | Neither primitive is designed for 60fps imperative loops |
Detailed Comparison
Signals: what they're good at
Signals are synchronous containers with automatic dependency tracking. They shine when:
- You need a current value that's always available (no
undefinedinitial state) - The value is derived from other values (
computed()) - The template reads the value directly (no
asyncpipe ceremony) - The state is local to a component or a small subtree
// Perfect Signal use case: local UI state
@Component({
template: `
<div [class.expanded]="isExpanded()">
<button (click)="toggle()">{{ isExpanded() ? 'Collapse' : 'Expand' }}</button>
<div *ngIf="isExpanded()">
<p>Showing {{ filteredItems().length }} of {{ items().length }} items</p>
<div *ngFor="let item of filteredItems()">{{ item.name }}</div>
</div>
</div>
`
})
export class CollapsibleListComponent {
items = input.required<Item[]>();
isExpanded = signal(false);
searchTerm = signal('');
filteredItems = computed(() =>
this.items().filter(i =>
i.name.toLowerCase().includes(this.searchTerm().toLowerCase())
)
);
toggle() {
this.isExpanded.update(v => !v);
}
}
Zero subscriptions. Zero cleanup. The dependency graph is implicit and automatic.
Observables: what they're good at
Observables are lazy, push-based streams with a rich operator library. They shine when:
- Values arrive asynchronously over time
- You need operators —
debounceTime,switchMap,retry,takeUntil,merge - You need cancelation (unsubscribing cancels in-flight HTTP requests)
- You're coordinating multiple async sources (
combineLatest,forkJoin,race) - You're working with event streams that produce many values
// Perfect Observable use case: coordinated async with operators
@Injectable({ providedIn: 'root' })
export class SearchService {
constructor(private http: HttpClient) {}
search(term$: Observable<string>): Observable<SearchResult[]> {
return term$.pipe(
debounceTime(300),
distinctUntilChanged(),
filter(term => term.length >= 2),
switchMap(term =>
this.http.get<SearchResult[]>(`/api/search?q=${term}`).pipe(
catchError(() => of([]))
)
)
);
}
}
No Signal equivalent exists for debounceTime or switchMap. These are fundamentally stream operations.
Where they overlap
Both can hold and propagate state. The overlap zone is shared application state — things like a user service, a cart, or a feature flag store. In this zone, either works, and the choice depends on your team's existing patterns:
| Pattern | Observable approach | Signal approach |
|---|---|---|
| Shared state | BehaviorSubject in a service |
signal() in a service |
| Derived state | combineLatest + map |
computed() |
| Template binding | | async |
Direct call value() |
| Cleanup | takeUntilDestroyed(), ngOnDestroy |
Automatic |
The Interop Bridge
toSignal() — Observable to Signal
Converts an Observable into a Signal. Subscribes immediately, updates the Signal on each emission, unsubscribes when the injection context is destroyed.
import { toSignal } from '@angular/core/rxjs-interop';
// Basic: with initial value
users = toSignal(this.userService.getAll(), { initialValue: [] });
// With undefined initial (type includes undefined)
user = toSignal(this.route.paramMap.pipe(
map(p => p.get('id'))
));
// Type: Signal<string | null | undefined>
// Require sync source (e.g., BehaviorSubject)
count = toSignal(this.counter$, { requireSync: true });
// Type: Signal<number> — no undefined
When to use: You have an Observable (HTTP, route, store selector) but want to read it synchronously in the template without async.
Gotchas:
- Must be called in an injection context (constructor, field initializer, or
runInInjectionContext) - The subscription lives until the component/service is destroyed — you can't manually unsubscribe
- For hot Observables that never complete, this is fine. For Observables you only need temporarily, keep using
subscribe()+takeUntilDestroyed()
toObservable() — Signal to Observable
Converts a Signal into an Observable that emits whenever the Signal's value changes.
import { toObservable } from '@angular/core/rxjs-interop';
searchTerm = signal('');
// Convert to Observable so we can use RxJS operators
results = toSignal(
toObservable(this.searchTerm).pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap(term =>
term.length < 2
? of([])
: this.searchService.search(term)
)
),
{ initialValue: [] }
);
When to use: You have a Signal (user input, local state) but need RxJS operators before consuming the value.
Gotchas:
toObservable()emits asynchronously (viaeffect()internally), not synchronously on.set()- Must also be called in an injection context
- The first emission happens asynchronously after the current microtask, not immediately
The "sandwich" pattern
The most common interop pattern is the Signal-Observable-Signal sandwich:
- Signal captures user input (synchronous)
toObservable()feeds it into an RxJS pipeline (async operators)toSignal()brings the result back for the template (synchronous read)
@Component({
template: `
<input (input)="onSearch($event)">
@if (results().length > 0) {
@for (r of results(); track r.id) {
<div class="result">{{ r.title }}</div>
}
} @else if (searchTerm().length >= 2) {
<p>No results found.</p>
}
`
})
export class SearchComponent {
private searchService = inject(SearchService);
// 1. Signal: synchronous input state
searchTerm = signal('');
// 2. Observable: async pipeline with operators
private results$ = toObservable(this.searchTerm).pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap(term =>
term.length < 2
? of([])
: this.searchService.search(term)
)
);
// 3. Signal: back to synchronous for template
results = toSignal(this.results$, { initialValue: [] });
onSearch(event: Event) {
this.searchTerm.set((event.target as HTMLInputElement).value);
}
}
Migration Playbook
Step 1: Identify what to migrate
Not everything needs to change. Categorize your reactive code:
| Category | Action |
|---|---|
BehaviorSubject in components |
Migrate to signal() |
combineLatest + map for derived state |
Migrate to computed() |
| async in templates |
Migrate to toSignal() |
HTTP services returning Observable |
Keep as Observable |
| NgRx selectors | Use selectSignal() or toSignal(store.select(...)) |
| Complex RxJS pipelines (debounce, retry, merge) | Keep as Observable |
Subject for events/actions |
Keep as Observable (or use output()) |
Step 2: Migrate component-local state
Before: BehaviorSubject
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-container *ngIf="{ count: count$ | async, doubled: doubled$ | async } as vm">
<p>Count: {{ vm.count }}</p>
<p>Doubled: {{ vm.doubled }}</p>
<button (click)="increment()">+1</button>
</ng-container>
`
})
export class CounterComponent {
private countSubject = new BehaviorSubject(0);
count$ = this.countSubject.asObservable();
doubled$ = this.count$.pipe(map(c => c * 2));
increment() {
this.countSubject.next(this.countSubject.getValue() + 1);
}
}
After: Signal
@Component({
template: `
<p>Count: {{ count() }}</p>
<p>Doubled: {{ doubled() }}</p>
<button (click)="increment()">+1</button>
`
})
export class CounterComponent {
count = signal(0);
doubled = computed(() => this.count() * 2);
increment() {
this.count.update(c => c + 1);
}
}
What changed:
BehaviorSubject+.asObservable()+.getValue()+.next()→signal()+.set()/.update()pipe(map(...))→computed()| async→ direct()callngIf as vmwrapper → gone- No more
OnPushneeded (Signals handle it automatically)
Step 3: Migrate service state
Before:
@Injectable({ providedIn: 'root' })
export class CartService {
private items$ = new BehaviorSubject<CartItem[]>([]);
readonly cartItems$ = this.items$.asObservable();
readonly count$ = this.items$.pipe(
map(items => items.reduce((sum, i) => sum + i.qty, 0))
);
readonly total$ = this.items$.pipe(
map(items => items.reduce((sum, i) => sum + i.price * i.qty, 0))
);
addItem(product: Product) {
const current = this.items$.getValue();
// ... update logic
this.items$.next(updated);
}
}
After:
@Injectable({ providedIn: 'root' })
export class CartService {
private items = signal<CartItem[]>([]);
readonly cartItems = this.items.asReadonly();
readonly count = computed(() =>
this.items().reduce((sum, i) => sum + i.qty, 0)
);
readonly total = computed(() =>
this.items().reduce((sum, i) => sum + i.price * i.qty, 0)
);
addItem(product: Product) {
this.items.update(current => {
// ... update logic
return updated;
});
}
}
Components consuming the service:
// Before:
count$ = this.cart.count$;
// template: {{ count$ | async }}
// After:
count = this.cart.count;
// template: {{ count() }}
Step 4: Migrate template patterns
| Before (Observable) | After (Signal) |
|---|---|
{{ value$ | async }} |
{{ value() }} |
*ngIf="value$ | async as val" |
@if (value(); as val) |
*ngFor="let item of items$ | async" |
@for (item of items(); track item.id) |
[class.active]="(active$ | async)" |
[class.active]="active()" |
(click)="subject.next($event)" |
(click)="handler($event)" |
Step 5: Migrate NgRx access
// Before:
users$ = this.store.select(selectAllUsers);
loading$ = this.store.select(selectUsersLoading);
// template: *ngIf="loading$ | async"
// After (option A — toSignal):
users = toSignal(this.store.select(selectAllUsers), { initialValue: [] });
loading = toSignal(this.store.select(selectUsersLoading), { initialValue: false });
// After (option B — selectSignal, NgRx 17+):
users = this.store.selectSignal(selectAllUsers);
loading = this.store.selectSignal(selectUsersLoading);
// template: @if (loading()) { ... }
Actions and effects stay Observable-based — they're inherently async stream operations.
Patterns to Avoid
Don't wrap every Observable in toSignal()
// BAD: wrapping a one-shot HTTP call you only need in ngOnInit
data = toSignal(this.http.get('/api/data'));
// BETTER: if you only need it once, just subscribe
ngOnInit() {
this.http.get('/api/data').subscribe(data => {
this.processData(data);
});
}
// OR: if the template needs it, toSignal is fine
data = toSignal(this.http.get<Data>('/api/data'));
toSignal() is great when the template consumes the value. For side-effect-only operations (analytics, logging, imperative DOM manipulation), keep using subscribe().
Don't use effect() as a subscription replacement
// BAD: using effect to replicate subscribe behavior
constructor() {
effect(() => {
const users = this.users();
this.processUsers(users); // side effect every time users change
});
}
// BETTER: if this is async work, keep it as an Observable pipeline
ngOnInit() {
toObservable(this.users).pipe(
switchMap(users => this.processAsync(users)),
takeUntilDestroyed()
).subscribe();
}
Don't mix imperative and reactive for the same state
// BAD: split brain — who owns this state?
count = signal(0);
count$ = new BehaviorSubject(0);
increment() {
this.count.update(c => c + 1);
this.count$.next(this.count()); // manual sync — fragile
}
// GOOD: pick one, bridge if needed
count = signal(0);
count$ = toObservable(this.count); // derived, always in sync
Advanced Interop Patterns
Signal-driven HTTP with resource()
Angular 19+ provides resource() as a declarative alternative to toSignal() + switchMap:
// Before: Observable sandwich
userId = signal(1);
private user$ = toObservable(this.userId).pipe(
switchMap(id => this.http.get<User>(`/api/users/${id}`))
);
user = toSignal(this.user$);
// After: resource()
userId = signal(1);
userResource = resource({
request: () => this.userId(),
loader: ({ request: id }) =>
fetch(`/api/users/${id}`).then(r => r.json())
});
// Template: {{ userResource.value()?.name }}
// Loading: {{ userResource.isLoading() }}
// Error: {{ userResource.error() }}
takeUntilDestroyed() — the missing piece
When you do need to subscribe to an Observable in a component (for side effects), takeUntilDestroyed() replaces the destroy$ + takeUntil + ngOnDestroy pattern:
// Before:
private destroy$ = new Subject<void>();
ngOnInit() {
this.route.params.pipe(
takeUntil(this.destroy$)
).subscribe(params => { /* ... */ });
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
// After:
constructor() {
this.route.params.pipe(
takeUntilDestroyed()
).subscribe(params => { /* ... */ });
}
takeUntilDestroyed() uses the injection context's DestroyRef to automatically complete the Observable when the component is destroyed. Call it in the constructor or field initializer.
outputFromObservable() and outputToObservable()
Bridge component outputs between the two worlds:
import { outputFromObservable, outputToObservable } from '@angular/core/rxjs-interop';
// Expose an Observable as a component output
@Component({ /* ... */ })
export class TimerComponent {
private tick$ = interval(1000);
tick = outputFromObservable(this.tick$);
}
// Convert a signal-based output to an Observable for testing
const tick$ = outputToObservable(component.tick);
tick$.subscribe(value => console.log('Tick:', value));
Migration Checklist
Use this checklist when migrating a component:
- Identify all
BehaviorSubjectfields → replace withsignal() - Identify all
.pipe(map(...))derived state → replace withcomputed() - Identify all
| asyncin the template → replace with()calls - Identify all
subscribe()calls:- Template data? → use
toSignal()instead - Side effects? → keep
subscribe(), addtakeUntilDestroyed()
- Template data? → use
- Identify all
combineLatest/forkJoinfor template data → replace with multiplecomputed()ortoSignal()calls - Remove
ngOnDestroy/destroy$cleanup if no longer needed - Remove
ChangeDetectionStrategy.OnPushif fully on Signals (optional — it still helps) - Run tests — behavior should be identical
Try It Yourself -- Pattern Converter
Select a common Angular pattern and see the Observable version side by side with the Signal equivalent. Each example highlights what changed and why.
When NOT to Migrate
Keep Observables when:
- The code works and isn't changing. Migration for migration's sake adds risk with no user benefit.
- You're deep in RxJS operator chains. Signals have no equivalent for
switchMap,exhaustMap,retryWhen,bufferTime, etc. - You're in an NgRx effect. Effects are fundamentally Observable pipelines. Keep them that way.
- Third-party libraries return Observables.
HttpClient,ActivatedRoute,FormControl.valueChanges— wrap withtoSignal()at the consumption point, not at the source.
The goal is not "zero Observables." The goal is using the right primitive for each job: Signals for synchronous state, Observables for async streams, and the interop bridge where they meet.
What's Next
With both reactivity systems under your belt, the next article shifts to Angular's visual layer — Material Theming. You'll learn how design tokens, custom palettes, and CSS custom properties work together, and how to wire up dynamic theme switching using the Signals patterns from this article.