Sub topic 3
When `toObservable` Emits and Why Values Can Be Skipped
Assume basic Angular dependency injection, signals, RxJS operators, and TypeScript. toObservable converts a signal into an RxJS Observable, which is a stream that consumers can subscribe to.
When `toObservable` emits
toObservable tracks the signal inside an Angular effect. The observable emits asynchronously when that effect runs. It does not emit synchronously for every call to set.
import { Component, signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-demo',
template: '',
})
export class Demo {
query = signal('');
constructor() {
toObservable(this.query).subscribe((value) => {
console.log(value);
});
this.query.set('a');
this.query.set('ab');
this.query.set('abc');
}
}The subscriber can receive only the latest value, abc, after Angular runs the effect. Intermediate values set during the same turn can be skipped. This behavior is useful because downstream work sees stabilized state instead of every synchronous mutation.
Building a debounced search
A signal can hold input state, RxJS can handle timing and cancellation, and another signal can expose results to the template.
import { Component, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs';
@Component({
selector: 'app-search',
template: `
<input (input)="query.set($any($event.target).value)" />
<ul>
@for (result of results(); track result) {
<li>{{ result }}</li>
}
</ul>
`,
})
export class Search {
private http = inject(HttpClient);
query = signal('');
results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((query) =>
this.http.get<string[]>('/api/search', { params: { q: query } }),
),
),
{ initialValue: [] },
);
}debounceTime waits until typing pauses. distinctUntilChanged ignores repeated text. switchMap cancels the previous request when a newer query arrives.
Common pitfalls and when not to convert
- Do not expect
toObservableto emit synchronously afterset. - Do not use
toSignalortoObservablein an ordinary method without an injection context. Create them in a constructor or field initializer, or pass anInjector. - Handle source errors before calling
toSignalif the template must remain readable. A signal created from an errored observable throws when read. - Avoid conversion when the data already fits the consumer. Use a signal for local synchronous state and an observable for stream operators, cancellation, or events.
Testing mixed code
Use fakeAsync and tick for debouncing. Test the signal output after the observable pipeline has had time to emit.
it('updates results after the debounce period', fakeAsync(() => {
const fixture = TestBed.createComponent(Search);
const component = fixture.componentInstance;
component.query.set('angular');
tick(299);
expect(component.results()).toEqual([]);
tick(1);
http.expectOne((request) => request.params.get('q') === 'angular')
.flush(['Angular Signals']);
expect(component.results()).toEqual(['Angular Signals']);
}));Exercise
If a signal is set to "a" and then "ab" in the same synchronous turn, which value should a toObservable subscriber generally receive?
Show answer
It should generally receive the stabilized latest value, "ab", when Angular runs the effect.