Sub topic 1
Mixing RxJS and Signals in Angular with `toSignal` and `toObservable`
Prerequisites
You should know basic Angular components and dependency injection, signals created with signal(), and RxJS observables, subscriptions, and operators.
Signals and observables: different tools for different jobs
A signal holds a current value. Angular can track reads of that value and update a template when it changes. Read a signal by calling it, such as count().
An observable represents values that arrive over time. It can be lazy, produce many values, and use RxJS operators such as map, debounceTime, and switchMap. Code receives its values after subscribing.
Use a signal for current application or UI state. Use an observable for asynchronous streams, events, timers, and request pipelines. Angular's RxJS interop functions connect these models.
Why the interop functions need an injection context
An injection context is an Angular-managed place where dependency injection and lifecycle cleanup are available. Component constructors, service constructors, and field initializers normally run in one.
toSignal uses that context to subscribe to the observable and automatically unsubscribe when the owning component or service is destroyed. If you call it in a regular method, pass an Injector explicitly.
Turning an observable into a signal with `toSignal`
toSignal subscribes immediately and returns a signal containing the latest emitted value.
import { Component } from '@angular/core';
import { interval } from 'rxjs';
import { toSignal } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-ticker',
template: `<p>Seconds: {{ seconds() }}</p>`,
})
export class Ticker {
seconds = toSignal(interval(1000), { initialValue: 0 });
}The signal starts at 0, then changes as the interval emits.
Handling the first value: `initialValue` and `requireSync`
Many observables do not emit immediately. Without an option, toSignal has the type Signal<number | undefined> because no value exists before the first emission.
Use initialValue when a temporary value makes sense. Use requireSync when the source is guaranteed to emit synchronously, as a BehaviorSubject does.
import { BehaviorSubject } from 'rxjs';
import { toSignal } from '@angular/core/rxjs-interop';
const source$ = new BehaviorSubject(0);
const count = toSignal(source$, { requireSync: true });
// count has type Signal<number>requireSync throws if the observable fails to emit during subscription. Choose either initialValue or requireSync; they describe different source behaviors.
Exercise
Which option should you use for an HTTP observable that emits later: initialValue or requireSync?
Show answer
Use initialValue, because an HTTP observable normally does not emit synchronously when subscribed.