RxJS & Angular Signals: Bridging Async Streams and Synchronous State
Signal & RxJS Interop: Combine both tools fluidly with toSignal() and toObservable() whenever you need to bridge data streams.
A common misconception when Signals arrived in Angular was that they were meant to replace RxJS entirely. In practice, they solve two different problems:
- **RxJS handles asynchronous event choreography:** Race conditions, debounce thresholds, multi-step HTTP retries, and real-time WebSocket feeds over time.
- **Signals handle synchronous state representation:** Holding values in memory, computing derived state without subscriptions, and driving fine-grained template updates.
- Instead of choosing one over the other, modern Angular pairs them using two bridge functions from @angular/core/rxjs-interop: toSignal() and toObservable().
## 1. Signals vs. Observables
| Dimension | RxJS Observable (Observable<T>) | Angular Signal (Signal<T>) |
| --- | --- | --- |
| Mental Model | Asynchronous stream of events over time | Synchronous container holding a current value |
| Value Availability | Might emit immediately, later, or never | Always returns a value synchronously |
| Cleanup | Requires manual unsubscription or takeUntilDestroyed | Automatically managed by Angular's dependency graph |
| Template Binding | Requires async pipe or manual subscription | Direct evaluation: \{\{ value() \}\} |
| Best Used For | WebSockets, debouncing, buffering, cancellation | View models, UI state, computed data, inputs |
## 2. Stream to State: toSignal()
toSignal() subscribes to an RxJS Observable under the hood and surfaces its latest emitted value as an Angular Signal.
### 2.1 The Old Boilerplate
Historically, feeding an Observable into a view required either boilerplate class subscriptions or scattering | async pipes across template tags:
```ts
// Legacy: Manual subscription handling & cleanup
export class LegacyUserComponent implements OnInit, OnDestroy {
private sub?: Subscription;
user: User | null = null;
constructor(private userService: UserService) {}
ngOnInit() {
this.sub = this.userService.getUser().subscribe(u => this.user = u);
}
ngOnDestroy() {
this.sub?.unsubscribe();
}
}
```
### 2.2 Modern Syntax with toSignal()
toSignal() subscribes immediately and ties teardown to the enclosing component or service lifecycle automatically:
```ts
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { UserService } from '../services/user.service';
@Component({
selector: 'app-user-profile',
standalone: true,
template: `
@if (user(); as currentUser) {
} @else {
user = toSignal(this.userService.getUser());
}
```
### 2.3 The Initial Value Problem
Observables are fundamentally asynchronous—they might not emit the moment you subscribe. Signals, on the other hand, must return a value synchronously when read.
toSignal() handles this with three options:
### Option 1: Default Behavior (undefined)
Without options, the signal initializes as undefined until the first emission:
```ts
// Type: Signal
products = toSignal(this.productService.getProducts$());
```
### Option 2: Provide an initialValue
Supply an immediate fallback to keep the type clean and avoid undefined checks:
```ts
// Type: Signal (never undefined)
products = toSignal(this.productService.getProducts$(), {
initialValue: []
});
```
### Option 3: Enforce Synchronous Emission (requireSync: true)
When converting an Observable guaranteed to emit synchronously upon subscription (such as a BehaviorSubject or an Observable starting with startWith()), enforce it:
```ts
import { BehaviorSubject } from 'rxjs';
const activeTheme$ = new BehaviorSubject<'light' | 'dark'>('light');
// Type: Signal<'light' | 'dark'>
theme = toSignal(activeTheme$, { requireSync: true });
```
- **Caution:** Setting requireSync: true on an asynchronous stream (like a standard HttpClient.get() request) causes Angular to throw a runtime error, because the signal cannot produce a value on creation.
### 2.4 Error Handling with rejectErrors
By default, if the source Observable emits an unhandled error, toSignal() catches it and re-throws the error the next time the signal is invoked.
Passing \{ rejectErrors: true \} instructs the signal to raise that exception immediately, allowing it to bubble straight up to Angular's global ErrorHandler:
```ts
data = toSignal(this.apiService.fetchCriticalData$(), {
rejectErrors: true
});
```
## 3. State to Stream: toObservable()
toObservable() turns an Angular Signal into an RxJS Observable. Each time the signal value updates, the Observable emits that new value downstream.
### 3.1 Why Convert a Signal to an Observable?
Signals alone don't handle timing constraints. When you need to debounce keystrokes, cancel in-flight HTTP requests, or coordinate multiple asynchronous streams, convert the signal into an RxJS pipeline:
```ts
import { Component, signal, inject } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http';
import { debounceTime, distinctUntilChanged, switchMap, filter } from 'rxjs';
@Component({
selector: 'app-live-search',
standalone: true,
template: `
{{ currentUser.name }}
{{ currentUser.email }}
Loading user details...
} ` }) export class UserProfileComponent { private userService = inject(UserService); // Subscribes immediately; unsubscribes automatically when component destroys // Type: Signal-
@for (item of searchResults(); track item.id) {
- {{ item.title }} } @empty {
- No results found. }
