Right Tool for the Job: Signals for State, RxJS for Events
Right Tool for the Job: Keep RxJS where it genuinely shines—complex async events, debounced search inputs, and cancellation flows—while letting Signals handle local state.
When Angular introduced Signals, a common takeaway was that RxJS was heading out the door. In practice, treating Signals as a 1:1 replacement for RxJS leads to messy, imperative code.
They solve fundamentally different architectural challenges:
- **Signals manage state:** Synchronous values, pure derivations, template bindings, and fine-grained DOM updates.
- **RxJS orchestrates events over time:** Race conditions, debouncing keystrokes, retries, polling intervals, cancellation, and streams.
- Writing clean modern Angular comes down to recognizing the boundary between state and events, and using the right primitive for each.
```text
1. The Core Divide: State vs. Events
┌────────────────────────────────────────────────────────────────────────┐
│ SYNCHRONOUS STATE │
│ "What is the current value right now?" │
├────────────────────────────────────────────────────────────────────────┤
│ • Best tool: Signals (signal, computed, input, model) │
│ • Nature: Always has a value, pull-based, glitch-free, synchronous │
│ • Use cases: Modal open/closed, active tab, counters, theme flags, │
│ derived cart totals │
└────────────────────────────────────────────────────────────────────────┘
```
```text
┌────────────────────────────────────────────────────────────────────────┐
│ ASYNCHRONOUS EVENTS │
│ "How do values transform, coordinate, and cancel over time?" │
├────────────────────────────────────────────────────────────────────────┤
│ • Best tool: RxJS (Observable, Subject, pipe operators) │
│ • Nature: Push-based, emits 0 to ∞ values, timing-aware, cancellable │
│ • Use cases: Search typeaheads, polling intervals, WebSocket streams, │
│ drag-and-drop coordinates, retry on failure │
└────────────────────────────────────────────────────────────────────────┘
```
## 2. Where Signals Shine: Synchronous UI State
Signals belong wherever state is read synchronously by templates or derived formulas.
### 2.1 The Legacy Anti-Pattern: RxJS for Everything
In older Angular apps, simple component variables were often wrapped in BehaviorSubject. Deriving a basic total meant writing combineLatest, piping operators, and dealing with streams inside classes:
```ts
// ❌ OVER-ENGINEERED: Using RxJS for synchronous local state
export class LegacyCartComponent {
private count$ = new BehaviorSubject(1);
private price$ = new BehaviorSubject(50);
// Heavy stream plumbing just to multiply two numbers
total$ = combineLatest([this.count$, this.price$]).pipe(
map(([count, price]) => count * price)
);
increment(): void {
this.count$.next(this.count$.value + 1);
}
}
```
### 2.2 The Modern Pattern: Plain Signals
With Signals, component state is readable, synchronous, and glitch-free:
```ts
// ✅ CLEAN: Signals for synchronous UI state
export class ModernCartComponent {
count = signal(1);
price = signal(50);
// Memoized, synchronous derived state
total = computed(() => this.count() * this.price());
increment(): void {
this.count.update(c => c + 1);
}
}
```
## 3. Where RxJS Genuinely Shines: Complex Async & Timing
Attempting to handle time, debouncing, or cancellation with Signals alone forces you into fragile setTimeout loops and race conditions. This is where RxJS remains essential.
### 3.1 Scenario 1: Debounced Search with Request Cancellation (switchMap)
### The Problem
A user types "ang", then quickly continues to "angular". Two HTTP calls fire. If the first request ("ang") resolves after the second ("angular"), it overwrites the newer data—a classic race condition.
### Why RxJS Wins
switchMap automatically cancels the obsolete in-flight HTTP request when a new search string arrives, while debounceTime keeps the app from spamming the backend on every keypress:
```ts
// src/app/features/search/user-search.component.ts
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toSignal, toObservable } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, switchMap, filter, catchError, of, map } from 'rxjs';
export interface User {
id: number;
name: string;
email: string;
}
@Component({
selector: 'app-user-search',
standalone: true,
template: `
`
})
export class UserSearchComponent {
private http = inject(HttpClient);
// 1. Local state managed by a Signal
query = signal('');
// 2. RxJS pipeline coordinates timing, filtering, and request cancellation
private searchResults$ = toObservable(this.query).pipe(
debounceTime(300),
map(text => text.trim()),
filter(text => text.length >= 2),
distinctUntilChanged(),
switchMap(search =>
this.http.get(`/api/users?q=${search}`).pipe(
catchError(() => of([])) // Resilient fallback
)
)
);
// 3. Bridged back to a Signal for clean template reads
users = toSignal(this.searchResults$, { initialValue: [] });
}
```
### 3.2 Scenario 2: Polling with Exponential Backoff
### The Problem
A dashboard needs live exchange rates every 5 seconds. If the network drops, it should retry 3 times with progressive delays (1s, 2s, 3s) before surfacing an error.
### Why Signals Struggle Here
Handling exponential backoff, polling intervals, and cleanup using setInterval and effect() requires tracking timers, retry counters, and manual teardown.
### The RxJS Solution
```ts
// src/app/services/exchange-rate.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { timer, retry, switchMap, shareReplay } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class ExchangeRateService {
private http = inject(HttpClient);
// Emits immediately, then every 5000ms; retries up to 3 times with progressive delay
readonly rates$ = timer(0, 5000).pipe(
switchMap(() => this.http.get>('/api/rates')),
retry({
count: 3,
delay: (error, retryCount) => timer(retryCount * 1000)
}),
shareReplay(1) // Share the active stream among multiple subscribers
);
}
Consume it cleanly in the component using toSignal():
```
```ts
@Component({
template: `Current USD Rate: {{ rates()?.['USD'] ?? 'Loading...' }}`
})
export class RateWidgetComponent {
private rateService = inject(ExchangeRateService);
rates = toSignal(this.rateService.rates$);
}
```
### 3.3 Scenario 3: Coordinating Parallel Async Requests
### The Problem
A page requires both /profile and /permissions data to render, and needs a "Refresh" trigger to refetch both in parallel.
### The RxJS Solution
```ts
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toSignal } from '@angular/core/rxjs-interop';
import { Subject, forkJoin, startWith, switchMap } from 'rxjs';
@Component({ ... })
export class AccountOverviewComponent {
private http = inject(HttpClient);
private refreshTrigger$ = new Subject();
private accountData$ = this.refreshTrigger$.pipe(
startWith(undefined), // Initial fetch on load
switchMap(() =>
forkJoin({
profile: this.http.get('/api/profile'),
permissions: this.http.get('/api/permissions')
})
)
);
accountData = toSignal(this.accountData$);
refresh(): void {
this.refreshTrigger$.next();
}
}
```
## 4. Decision Matrix: Signals vs. RxJS
| Requirement / Scenario | Use | Why? |
| --- | --- | --- |
| Component UI state (tabs, toggles, filters) | Signals | Synchronous, straightforward mutation via .set(), zero stream overhead. |
| Derived calculations (tax, totals, sorting) | computed() | Glitch-free, memoized, re-runs only when tracked dependencies change. |
| Two-way bindings & forms | model() / Forms | Built-in two-way synchronization without managing subjects. |
| Debounce, throttle, delay | RxJS | Built-in operators (debounceTime, auditTime, delay). |
| Request cancellation / Race conditions | RxJS | switchMap cancels obsolete async work natively. |
| Parallel or queued async tasks | RxJS | forkJoin, concatMap, mergeMap, and zip. |
| Streaming real-time feeds | RxJS | Ideal for WebSockets, SSE, and recurring interval timers. |
| Template rendering | Signals | Direct execution: `{{ value() }}`; no `async` pipe needed. |
## 5. The "Sandwich Pattern": Architecture in Practice
The cleanest architecture in modern Angular projects follows the Signal-RxJS-Signal Sandwich:
```text
[ USER INPUT / LOCAL STATE ] ──> Signals (signal, input, model)
│
toObservable()
│
▼
[ ASYNC LOGIC & COORDINATION ] ──> RxJS Pipeline (debounce, switchMap, retry)
│
toSignal()
│
▼
[ TEMPLATE / CONSUMPTION ] ──> Signals (read directly in HTML)
```
- **Top Layer (Signals):** The UI captures user actions and stores active parameters in Signals (searchQuery, pageIndex, selectedFilter).
- **Middle Layer (RxJS):** When asynchronous coordination is required, turn the Signal into an Observable with toObservable(), apply operators (switchMap, debounceTime, retry), and communicate with services or network APIs.
- **Bottom Layer (Signals):** Bridge the resulting stream back to a Signal with toSignal() so templates can render values synchronously with zero subscription boilerplate.
-
@for (user of users(); track user.id) {
- {{ user.name }} ({{ user.email }}) } @empty { @if (query().length >= 2) {
- No users found. } }
