
Signals vs RxJS: State vs Events, Not Old vs New
- كاتب موثّق
- Angular 22
محتويات المقال
debounceTime(300) and switchMap, becomes an effect that calls the API whenever query changes. Within a week, two bugs come in. Typing "laptop" sends a request for nearly every letter, and on a slow connection the results for "lap" sometimes arrive last and replace the results for "laptop".
The common misconception
input(), model(), viewChild(), resource(), and since v22 a stable httpResource(). Signals also remove ceremony: no subscribe(), no unsubscribing, no async pipe. And many Observables in Angular code really were state in disguise: a BehaviorSubject holding the cart, a combineLatest that only existed to compute a total. Converting those is a genuine improvement. The mistake is the word "every". Some Observables were never state.
What actually happens
A signal is a value; an Observable is a sequence of events
Object.is by default, notifies nobody. And values set between two reads are never seen: the interop guide sets a signal to 1, 2 and 3 in a row, and toObservable() emits only 3.
debounceTime), cancel (switchMap), merge or retry. So the useful question isn't "old or new?" but "state or event?". The current query, the selected product and the cart are state: only the latest value matters. A keystroke you want to wait out, a request that a newer one supersedes, a WebSocket message or a click you must count are events: each occurrence, and when it happened, matters.
The search box is both
import { Component, effect, inject, signal } from '@angular/core';@Component({ selector: 'app-product-search', templateUrl: './product-search.html',})export class ProductSearch { private readonly api = inject(ProductApi); readonly query = signal(''); readonly results = signal<Product[]>([]); constructor() { // A request per keystroke, and a slow old response can win effect(() => { this.api.search(this.query()).subscribe((r) => this.results.set(r)); }); }}import { Component, inject, signal } from '@angular/core';import { toObservable, toSignal } from '@angular/core/rxjs-interop';import { debounceTime, switchMap } from 'rxjs';@Component({ selector: 'app-product-search', templateUrl: './product-search.html',})export class ProductSearch { private readonly api = inject(ProductApi); readonly query = signal(''); // Events stay in RxJS; the template reads the latest result as a signal readonly results = toSignal( toObservable(this.query).pipe( debounceTime(300), switchMap((q) => this.api.search(q)), // cancels the stale request ), { initialValue: [] }, );}toObservable() turns the query into a stream. debounceTime(300) is a : it emits only after typing pauses for 300 ms. switchMap unsubscribes from the previous request when a new query arrives, and with HttpClient that unsubscription aborts the request, so a stale response can't overwrite a newer one. That's the gone. toSignal() subscribes once, unsubscribes when the component is destroyed, and the template reads results() like any other signal. One behavior to plan for: if the stream errors, toSignal() throws that error every time results() is read, and an Observable that has errored emits nothing more. A single failed request inside switchMap would break the search box for good, so catch errors inside the switchMap callback, for example by returning of([]) from catchError. If you don't need the debounce, rxResource() and httpResource() also cancel an outdated request and expose the result, the loading state and the error as signals.
Where signals do replace RxJS
BehaviorSubject so templates could read it through the async pipe is where signals clearly win:
import { Service, computed, signal } from '@angular/core';@Service()export class CartStore { // Was: a BehaviorSubject<CartLine[]> read with the async pipe private readonly lines = signal<CartLine[]>([]); readonly count = computed(() => this.lines().length); add(line: CartLine): void { this.lines.update((all) => [...all, line]); }}count is memoized instead of rebuilt by combineLatest and map, and there's no subscription to forget. Templates that read count() are updated when it changes, with nothing to wire up.
BehaviorSubject holding current state | signal() | |
combineLatest + map to derive a value | computed() | |
toSignal() | ||
How to apply it in your project
Sort your Observables For each one, ask: does anyone care about anything but the latest value? If not, it's state. If every emission or its timing matters, it's an event stream. Move state to signals Replace BehaviorSubjectstate containers withsignal(), and values derived withcombineLatestwithcomputed().Convert at the edge Where a template needs an Observable's latest value, call toSignal()once, in a field initializer, with aninitialValue, orrequireSync: truefor sources that emit synchronously, like aBehaviorSubject.Keep pipelines for time and cancellation Leave debouncing, switchMap, retries and event streams in RxJS, and feed them from signals withtoObservable().
Key takeaways
A signal answers "what's the value now?"; an Observable answers "what happened, and when?". Signals skip intermediate values and ignore equal ones: right for state, wrong for events. Move state to signal()andcomputed(); keep debouncing, cancellation and event streams in RxJS.Bridge the two with toSignal()andtoObservable()instead of rewriting a pipeline as an effect.
التعليقات (0)