Sub topic 8
When toObservable emits and why values can be skipped
This chapter assumes you can create and read signals with signal() and computed(), and that you know basic RxJS (subscribe, map, switchMap). It also assumes you have met toObservable and know it must run in an injection context. The chapter explains when toObservable emits, which values a subscriber never sees, and how to work with that behavior.
The core rule: emission comes from an effect
toObservable(signal) does not subscribe to the signal in the RxJS sense. A signal has no subscribers. Internally, toObservable does three things:
- It creates a
ReplaySubjectwith a buffer size of 1. - It creates an
effectthat reads your signal and pushes the current value into that subject. - It returns the subject as an observable. Destroying the injector's owner stops the effect and completes the subject.
Effects do not run when you write to a signal. They are scheduled and run later, during Angular's change detection and effect flushing. So toObservable inherits three properties from effects:
- It is asynchronous relative to your code.
set()returns before any subscriber is called. - It is coalesced. If you write to the signal several times before the effect runs, the effect reads the signal once and sees only the latest value.
- It starts late. The first emission happens when the effect first runs, not when you call
toObservableorsubscribe.
The skipped-values example
import { Component, signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-demo',
template: ``,
})
export class Demo {
n = signal(0);
constructor() {
toObservable(this.n).subscribe((v) => console.log('emitted', v));
this.n.set(1);
this.n.set(2);
setTimeout(() => {
this.n.set(3);
this.n.set(4);
}, 1000);
}
}The console shows:
emitted 2
emitted 4Three values are never emitted:
- 0: the initial value. The effect had not run yet when the constructor finished. When it did run, the signal already held 2.
- 1: it was overwritten by
set(2)before the effect ran. - 3: the same thing happened inside the
setTimeoutcallback.
The signal was never wrong. The observable only reports what the signal held at the moment the effect ran.
Timeline of one emission
What decides when the effect runs
The exact moment depends on where the toObservable call happened and on your Angular version. In practice, you can rely on these points:
| Situation | What to expect |
|---|---|
| Several `set()` calls in the same synchronous block | One emission with the last value |
| `set()` calls separated by an `await`, a timer, or another task, with change detection between them | One emission per change detection pass |
| Subscribing right after `toObservable(...)` | No synchronous emission. The first value arrives later |
| Subscribing after the effect has already run | Immediate replay of the latest value, because of the `ReplaySubject(1)` |
| The owning component or injector is destroyed | The observable completes |
If your code depends on an exact ordering, check it in your Angular version instead of assuming it. The reliable guarantees are that emissions are asynchronous, that they are coalesced, and that late subscribers get the latest value.
The same value can still be emitted twice
Signals skip notifications when you set a value equal to the current one, using Object.is by default. That check happens at write time. Consider this sequence inside one tick:
import { Component, signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
import { distinctUntilChanged } from 'rxjs';
@Component({
selector: 'app-flip',
template: ``,
})
export class Flip {
flag = signal(false);
constructor() {
toObservable(this.flag)
.pipe(distinctUntilChanged())
.subscribe((v) => console.log('flag', v));
setTimeout(() => {
this.flag.set(true);
this.flag.set(false);
}, 500);
}
}Both writes change the signal, so the effect is scheduled. When it runs, the value is false again, which equals the last value emitted. Without distinctUntilChanged(), the subscriber could receive a duplicate false. Adding distinctUntilChanged() removes any such duplicate. The operator costs almost nothing, so it is a good default when a downstream step is expensive, such as an HTTP request.
It is not a source for `requireSync`
toSignal(..., { requireSync: true }) demands that the observable emits synchronously when subscribed. toObservable does not do that. Combining them fails:
import { Component, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-broken',
template: `<p>{{ copy() }}</p>`,
})
export class Broken {
source = signal(1);
// Throws: toObservable has not emitted when toSignal subscribes.
copy = toSignal(toObservable(this.source), { requireSync: true });
}If you need a derived signal, use computed(). Going signal to observable to signal is only worthwhile when an RxJS operator does work that computed() cannot, such as debounceTime or switchMap. In that case, give toSignal an initialValue.
When skipping is fine and when it is not
Skipping is usually what you want. toObservable treats a signal as state, and state answers the question "what is the value now?" It does not answer "what happened?" Typical state cases:
- A search box that triggers a request. Only the final text matters.
- A selected item id that drives a detail view.
- A page number that drives a fetch.
Skipping causes problems when each value is an event that you must process:
- Counting how many times a button was clicked.
- Logging every keystroke for analytics.
- Applying a sequence of commands where each one has a side effect.
For events, use a Subject and call next() on each event. You can keep a signal next to it for state:
import { Component, signal } from '@angular/core';
import { Subject } from 'rxjs';
@Component({
selector: 'app-clicks',
template: `<button (click)="click()">Click</button> {{ total() }}`,
})
export class Clicks {
total = signal(0);
readonly clicks$ = new Subject<number>();
click() {
this.total.update((t) => t + 1);
// Every click is emitted, including ones in the same tick.
this.clicks$.next(this.total());
}
}The signal feeds the template, and the subject carries every event to any RxJS pipeline.
Combining skipping with `switchMap` and `debounceTime`
The skipping behavior lines up well with operators that discard intermediate values anyway. In the debounced search from the pipeline chapter, toObservable(this.query) already drops values written in the same tick. debounceTime(300) then drops values that arrive less than 300 ms apart. Both reduce the number of requests, but they work at different levels:
toObservablecoalescing works within one synchronous block. It is a side effect of effect scheduling, and you cannot configure it.debounceTimeworks over wall-clock time and is under your control.
Do not rely on coalescing as a replacement for debounceTime. Two keystrokes in separate tasks each run change detection and each produce an emission.
Practical checks when an emission seems missing
When a subscriber does not see a value you expect, work through these questions in order:
- Was the signal written more than once before change detection? If so, only the last value is emitted. This is expected.
- Was the written value equal to the current one? Signals ignore writes that match under their equality function, so no effect is scheduled.
- Did change detection ever run? If the application has not rendered yet, or you are in a unit test that never flushes effects, the effect has not executed.
- Was the
toObservablecall made in a context that has since been destroyed? The observable has completed and will not emit again. - Did you subscribe late? You get the latest value only, not the history.
In tests, you must trigger the effect yourself. Depending on your Angular version, that means calling TestBed.tick() or fixture.detectChanges(), or the older TestBed.flushEffects(). The testing chapter covers this in detail.
Reading the signal inside the pipeline
Another source of confusion is reading other signals inside operators. The effect tracks only the signal passed to toObservable. Reads inside map or switchMap callbacks happen in subscriber code, outside the effect, so they are not tracked and they see the value at the time the callback runs:
import { Component, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { map } from 'rxjs';
@Component({
selector: 'app-label',
template: `<p>{{ label() }}</p>`,
})
export class Label {
query = signal('');
prefix = signal('Result');
// Re-runs only when query changes, not when prefix changes.
label = toSignal(
toObservable(this.query).pipe(map((q) => `${this.prefix()}: ${q}`)),
{ initialValue: '' },
);
}If prefix changes alone, label does not update. To make both inputs trigger, build one signal from both with computed(), then pass it to toObservable:
import { Component, computed, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { map } from 'rxjs';
@Component({
selector: 'app-label2',
template: `<p>{{ label() }}</p>`,
})
export class Label2 {
query = signal('');
prefix = signal('Result');
private input = computed(() => ({ q: this.query(), p: this.prefix() }));
label = toSignal(
toObservable(this.input).pipe(map(({ q, p }) => `${p}: ${q}`)),
{ initialValue: '' },
);
}Because computed returns a new object whenever either input changes, the effect sees a change and emits.
Summary of behavior
toObservableemits from an effect, so emissions are asynchronous and tied to change detection.- Writes made before the effect runs are coalesced into one emission carrying the latest value.
- The initial value is emitted only if the effect runs while the signal still holds it.
- Late subscribers receive the latest value through the internal
ReplaySubject(1). - Use
distinctUntilChanged()to remove duplicates, and aSubjectfor events that must not be skipped. - Use
computed()to combine several signals into the one signal you convert.
Exercise
A component runs const n = signal(10); toObservable(n).subscribe(console.log); n.set(11); n.set(12); n.set(13); in its constructor. What does the subscriber log, and which values are never delivered?
Show answer
It logs only 13. The effect created by toObservable has not run when the constructor finishes. When it runs, it reads the current value, 13. The values 10, 11 and 12 are never delivered.
Exercise
You need to record every value a user types, even when two values are produced in the same synchronous block. Why is toObservable the wrong tool, and what would you use?
Show answer
toObservable coalesces writes made before its effect runs, so it delivers only the latest value. Use an RxJS Subject and call next() for each value. You can still keep a signal for the current state.
Exercise
Why does toSignal(toObservable(source), { requireSync: true }) throw, and how do you fix it?
Show answer
requireSync requires the observable to emit synchronously on subscription. toObservable emits later, from an effect. Replace it with computed() if no RxJS operator is needed, or provide an initialValue to toSignal instead of requireSync.
Exercise
In a pipeline toObservable(this.query).pipe(map((q) => this.prefix() + q)), changing only prefix does not update the result. Why, and how do you fix it?
Show answer
Only query is read by the effect inside toObservable. The prefix() read happens in the map callback, outside the effect, so it is not tracked. Combine both into one computed() signal and pass that to toObservable.