Sub topic 1
Signals and observables: different tools for different jobs
Angular now has two reactive primitives, and they overlap enough to cause confusion. A signal holds a value and tells Angular when that value changes. An RxJS observable describes a stream of values over time. Most real components need both. Before you convert between them with toSignal and toObservable (the later chapters), you need to know what each one is for. That way you can pick the right one, and you can tell when a conversion is unnecessary.
Prerequisites
This chapter assumes you already know the following:
- Basic Angular components and dependency injection, including
inject(). - How to create and read signals with
signal()andcomputed(). - Basic RxJS: what an
Observableis, howsubscribeworks, and common operators such asmapandswitchMap. - TypeScript, including generics such as
Signal<number>andObservable<string[]>.
You do not need to know anything about @angular/core/rxjs-interop yet. This chapter only prepares the ground for it.
What a signal is
A signal is a wrapper around a value. You read it by calling it as a function, and you change it with set or update. Angular tracks which signals a template, a computed, or an effect reads. When a signal changes, only the things that read it are notified.
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-cart',
template: `
<p>{{ count() }} items at {{ price() }} each: {{ total() }}</p>
<button (click)="add()">Add one</button>
`,
})
export class Cart {
count = signal(0);
price = signal(5);
total = computed(() => this.count() * this.price());
add() {
this.count.update((c) => c + 1);
}
}Four properties of signals matter for the rest of this tutorial.
- A signal always has a value.
signal(0)is0from the moment it exists. There is no "not yet emitted" state, so reading never returnsundefinedunless you putundefinedin the type. - Reading is synchronous.
count()returns the current value immediately. You can read it anywhere: in a template, in a method, in acomputed. - Derived values are lazy and cached.
totalis recalculated only when someone reads it aftercountorpricehas changed. Reading it twice in a row does not run the function twice. - Setting an equal value is a no-op. By default a signal compares the new value with the old one using
Object.is. If they are equal, nothing is notified.
A signal has no concept of time, of failure, or of ending. It has no "error" state and no "complete" state. It is a place where the latest value lives.
What an observable is
An observable is a description of a producer of zero or more values, delivered over time. Nothing happens until someone subscribes. Each subscription typically starts its own execution of the producer, and the producer can finish or fail.
import { interval, map, take } from 'rxjs';
const doubled$ = interval(1000).pipe(
take(3),
map((n) => n * 2),
);
doubled$.subscribe({
next: (v) => console.log('value', v),
error: (e) => console.error('failed', e),
complete: () => console.log('done'),
});
// After 1s: value 0
// After 2s: value 2
// After 3s: value 4, then doneObservables have three properties that signals do not.
- They may not have a value yet. Between subscribing and the first emission, there is nothing to read. An HTTP request returns its first value only when the response arrives.
- They have an error channel and a completion signal. A stream can end normally or fail, and every subscriber can react to each outcome.
- They are composed with time-aware operators.
debounceTime,switchMap,retry,combineLatest,takeUntil, and many others exist because streams of events need timing, ordering, and cancellation rules.
The cost is that you manage subscriptions. A subscription you forget to end can leak memory and keep running after its component is gone.
Comparing them side by side
| Question | Signal | Observable |
|---|---|---|
| Has a value at all times? | Yes | No, only after an emission |
| How do you read it? | Call it: `count()` | Subscribe, or use `async` pipe |
| Delivery | Synchronous read of current value | Push over time, sync or async |
| Can it error or complete? | No | Yes |
| Starts work when? | Value exists immediately | Usually when subscribed (lazy) |
| Cleanup | Handled by Angular's tracking | You unsubscribe, or tie it to a lifetime |
| Missed values | Only the latest matters | Every emission is delivered to subscribers |
| Best operators | `computed`, `effect` | RxJS operators |
The "missed values" row deserves attention because it is the root of several issues later in this tutorial. A signal represents state: only the current value matters, and intermediate values can be skipped. An observable represents events: every emission is a fact that happened, and each can matter.
If a signal goes from 1 to 2 to 3 within one synchronous block, a consumer that looks afterwards sees only 3. If an observable emits 1, 2, 3, every subscriber receives all three.
State versus events
A practical way to choose is to ask whether the thing you are modelling is state or an event stream.
- State answers "what is the value right now?" Examples: the selected tab, the text in a form field, whether a panel is open, the current page number. Signals fit, because templates and computed values need an answer at any moment.
- Events over time answer "what happened, and when?" Examples: keystrokes, WebSocket messages, route changes, HTTP responses, timers. Observables fit, because ordering, timing, and cancellation are part of the problem.
The same piece of data can be viewed both ways. The text in a search box is state (what is in the box now) and also an event stream (the user typed, paused, typed again). The two views are why you will convert between them.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-box',
template: `
<input (input)="text.set($any($event.target).value)" />
<p>You typed: {{ text() }}</p>
`,
})
export class Box {
// State view: the current text, always available to the template.
text = signal('');
}Showing the current text needs only the signal. Waiting 300 ms after the last keystroke before calling a server is an event-timing problem, and that is where RxJS earns its place.
Why the two do not simply replace each other
You may wonder whether signals could absorb everything RxJS does, or the reverse. Neither works well, for specific reasons.
Signals cannot express time. There is no debounce, no cancellation of an in-flight request when a new value arrives, no retry with backoff, and no merging of event sources by arrival order. You could build these by hand with effect and timers, but you would reimplement RxJS, and probably with more bugs.
Observables are awkward for plain state. To read the current value of an observable, you need a subscription, and you must handle the case where it has not emitted yet. A BehaviorSubject helps, but you then manage .value, .next(), and .asObservable() by hand, and derived values need combineLatest plus map where a computed would be one line.
Here is the same derived total written both ways.
import { BehaviorSubject, combineLatest, map } from 'rxjs';
import { computed, signal } from '@angular/core';
// RxJS version
const count$ = new BehaviorSubject(2);
const price$ = new BehaviorSubject(5);
const total$ = combineLatest([count$, price$]).pipe(
map(([count, price]) => count * price),
);
total$.subscribe((t) => console.log('rxjs total', t));
// Signal version
const count = signal(2);
const price = signal(5);
const total = computed(() => count() * price());
console.log('signal total', total());The signal version needs no subscription and no cleanup, and it can be read directly in a template. The RxJS version works, but needs a subscription for every consumer.
Signals have another advantage in templates. Angular's change detection can use signal reads to know exactly which views need updating. An observable in a template goes through the async pipe, which subscribes, stores the latest value, and asks Angular to re-check the view when it changes.
Where the boundary falls in a real app
In practice the boundary follows the data flow. Many Angular APIs still hand you observables: HttpClient, the router's events, reactive forms' valueChanges, and many third-party libraries. Your component templates and derived state are best expressed as signals. So a common architecture looks like this:
That block is not valid under the allowed constructs, so here is the diagram in the required form.
Observables handle the incoming, time-based part. Signals hold the result and feed the view. The bridge between the two is the topic of the rest of the tutorial: toSignal crosses from left to right, and toObservable crosses back when a signal's changes need RxJS operators.
A decision guide
Use these rules as defaults, not laws.
- Use a signal for component state, for values the template reads, and for anything derived from other state (
computed). If you find yourself asking "what is the value right now?", you want a signal. - Use an observable when you need time, ordering, or cancellation: debouncing input, cancelling stale requests, polling, retrying, merging event sources, or WebSocket streams. If you find yourself asking "what happens after this, and in what order?", you want an observable.
- Keep the type that the API gives you until you have a reason to convert. An
HttpClientcall returning one value does not have to become a signal at once. You can use theasyncpipe, or convert at the edge where the template needs a value. - Convert at boundaries, not everywhere. Each conversion adds a subscription, an injection-context requirement, and timing behaviour you must reason about. Pick one place where data crosses and keep the inside of each world pure.
Common misconceptions
"A signal is just a BehaviorSubject." They share the "always has a current value" idea, but a BehaviorSubject is also a stream: it delivers every next call to every subscriber, can error, and can complete. A signal skips intermediate values, has no error or completion, and is tracked automatically by Angular's reactivity graph rather than by subscriptions.
"I should convert every observable to a signal." Many streams are not state. A click stream or a stream of WebSocket messages has no meaningful "current value". Forcing it into a signal throws away every event except the latest.
"Signals make effect the new subscribe." An effect runs side effects when signals it reads change. It is not a general-purpose stream consumer, and it is not designed for setting other signals as a way to derive state. Derive with computed. Use effect for side effects such as logging or syncing to storage.
Where this leads
The rest of the tutorial builds on the split described here:
toSignalturns an observable into a signal so a template can read it synchronously. Because an observable may not have emitted yet, you will need to decide what the signal holds before the first value.toObservableturns a signal into an observable so you can apply RxJS operators. Because signals are state, intermediate values can be skipped, which affects when the observable emits.- Both functions manage subscriptions through Angular's injection context. Chapters later on cover how that context works and what to do when you have none.
- Putting both together gives the signal-to-stream-to-signal pipeline used for debounced search.
If you remember one thing from this chapter, make it this: signals model state, with a value at every moment, and observables model events over time, with ordering, errors, and completion. Every decision about conversion follows from that.
Exercise
A component needs (1) the currently selected tab index, shown in the template and used to compute a label, and (2) a stream of WebSocket messages where every message must be processed in order, even if several arrive at nearly the same time. Which of these should be a signal and which an observable, and why?
Show answer
The selected tab index is state: only the current value matters, the template needs it synchronously, and the label is derived from it with computed(). Use a signal. The WebSocket messages are events: each one is a separate fact and the order matters. A signal would keep only the latest value and could skip messages that arrive between reads, so use an observable (or a Subject) and process each emission with RxJS operators.
Exercise
A teammate writes const total$ = combineLatest([count$, price$]).pipe(map(([c, p]) => c * p)); using two BehaviorSubjects, and subscribes to it in three different components. Name two costs of this approach compared with computed(() => count() * price()) using signals.
Show answer
First, each of the three components needs its own subscription, so each one must be cleaned up (for example with the async pipe or takeUntil) or it can leak. Second, the value is only available after subscribing and in a callback, while a computed signal can be read synchronously at any point, including in the template, and is cached until count or price changes. Any consumer of the observable also has to handle the stream's error and completion channels, which a plain derived state value does not need.