Sub topic 4
Handling the first value: initialValue and requireSync
An observable may not have produced a value yet, but a signal always holds one. toSignal has to bridge that gap, and the initialValue and requireSync options are how you choose to do it. This chapter covers what each option does, how it changes the signal's type, and what goes wrong when you pick the wrong one.
This chapter assumes you can write Angular components with inject(), create signals with signal() and computed(), and use basic RxJS operators. It also assumes you have read the previous chapter on toSignal, including why it needs an injection context.
The problem: a signal must always have a value
Reading a signal returns a value immediately. Nothing about reading it can wait. An observable works differently. interval(1000) emits nothing for the first second, and an HTTP request emits nothing until the response arrives.
If toSignal subscribes to such an observable, the signal has nothing to hold for a while. By default, Angular fills that gap with undefined and widens the type to match.
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-default-demo',
template: `<p>Ticks: {{ ticks() }}</p>`,
})
export class DefaultDemo {
// Signal<number | undefined>
ticks = toSignal(interval(1000));
}For the first second, ticks() returns undefined. After that it returns 0, 1, 2 and so on. The type is Signal<number | undefined>, so every consumer must handle undefined. A computed signal that does this.ticks() + 1 fails to compile under strict settings, because the left side might be undefined.
You have three ways to deal with this:
- Accept the
undefinedand handle it everywhere the signal is read. - Pass
initialValueso the signal starts with a value you choose. - Pass
requireSync: trueto promise that the observable emits during subscription, so no gap exists.
Option 1: initialValue
initialValue is the value the signal holds until the observable emits its first value. It removes undefined from the type, unless the value you pass is itself undefined or null.
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-ticker',
template: `<p>Seconds: {{ seconds() }}</p>`,
})
export class Ticker {
// Signal<number>: initialValue removes undefined from the type.
seconds = toSignal(interval(1000), { initialValue: 0 });
}The template shows Seconds: 0 right away. One second later interval emits its first value, which is also 0. The signal then holds 1 after two seconds and so on.
initialValue is not an emission of the observable. It is only the starting state of the signal. If the observable happens to emit synchronously during subscription, that value replaces the initial value before any code can read it.
Choosing a value that means "not loaded yet"
For data that arrives later, the initial value often has to say "nothing here yet". null works well for single objects, and an empty array works for lists.
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { toSignal } from '@angular/core/rxjs-interop';
interface User {
name: string;
}
@Component({
selector: 'app-profile',
template: `
@if (user(); as u) {
<h2>{{ u.name }}</h2>
} @else {
<p>Loading...</p>
}
`,
})
export class Profile {
private http = inject(HttpClient);
// Signal<User | null>
user = toSignal(this.http.get<User>('/api/user'), { initialValue: null });
}Here the type is Signal<User | null>. This is better than the default User | undefined because null is something you chose on purpose. A reader of the code sees that null means "still loading". An undefined could also come from a bug.
A good initial value follows one rule. It must be a valid member of the type that your template and computed signals can handle without special cases. An empty array for a list needs no @if, because @for over an empty array renders nothing.
Option 2: requireSync
Some observables always emit during subscribe(), before the call returns. BehaviorSubject is the standard example, because it stores a current value and sends it to each new subscriber at once. For these sources, a gap never exists, so an initial value would be dead code.
requireSync: true tells toSignal that the observable will emit synchronously. The signal's type then has no undefined and no extra initial value.
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'app-counter',
template: `<p>{{ count() }}</p>`,
})
export class Counter {
private count$ = new BehaviorSubject(0);
// Signal<number>: requireSync is valid because BehaviorSubject emits synchronously on subscribe.
count = toSignal(this.count$, { requireSync: true });
}What happens when the promise is broken
requireSync is a check, not a conversion. After subscribing, toSignal looks to see whether a value arrived. If none did, it throws an error right away, at the line where you called toSignal, not later when you read the signal.
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Subject } from 'rxjs';
@Component({
selector: 'app-broken',
template: `<p>{{ value() }}</p>`,
})
export class Broken {
private source$ = new Subject<number>();
// Throws while the component is being created:
// a plain Subject does not emit on subscribe.
value = toSignal(this.source$, { requireSync: true });
}A failure at construction is useful. You find the mistake the first time the component renders, not in production when a particular timing occurs.
Sources that emit synchronously
| Source | Emits synchronously on subscribe? |
|---|---|
| `BehaviorSubject` | Yes, always |
| `of(1, 2, 3)` | Yes, and it completes |
| `ReplaySubject` with buffered values | Yes, but only if the buffer is not empty |
| `Subject` | No |
| `interval(1000)` | No |
| `HttpClient` requests | No |
| `fromEvent(...)` | No |
| Any source piped through `debounceTime`, `delay` or `observeOn` | No |
Be careful with the ReplaySubject row. The result depends on runtime state, so a requireSync call that works in one run can throw in another. If you cannot say with certainty that a value exists at subscription time, do not use requireSync.
Making a source synchronous with startWith
You can often turn an asynchronous source into a synchronous one by adding startWith. This operator emits one value at subscription time and then passes along the rest of the stream.
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval, startWith } from 'rxjs';
@Component({
selector: 'app-start-with',
template: `<p>{{ ticks() }}</p>`,
})
export class StartWithDemo {
// Signal<number>: startWith guarantees a synchronous first emission.
ticks = toSignal(interval(1000).pipe(startWith(0)), { requireSync: true });
}This gives the same result as initialValue: 0 for interval, with one difference. Here, the starting value is part of the stream. Other subscribers to the same piped observable would also see it. With initialValue, only the signal knows about the starting value.
Choosing between them
Use these rules:
- Use
requireSyncwhen the source is a state holder such as aBehaviorSubject, or when you control the pipe and have addedstartWith. - Use
initialValuefor anything that waits on time, the network or user events. - Use neither only when "no value yet" is a real state that the consumers should handle. Typical cases are an optional selection or a result that may never arrive.
Rules and edge cases
You cannot combine the two options. The types allow initialValue or requireSync, not both. They answer the same question in different ways. If you pass both, the code does not compile.
The initial value does not hide a failure. If the observable errors before emitting, reading the signal throws that error, even if you set initialValue. The initial value covers only the wait for a first value. The next chapter explains error handling in more detail.
Completion keeps the last value. If an observable completes after emitting, the signal keeps the last value. of(1, 2, 3) with requireSync: true gives a signal that holds 3. If the observable completes without ever emitting, then initialValue stays in place. With requireSync the call has already thrown.
An observable can emit undefined on purpose. new BehaviorSubject<string | undefined>(undefined) with requireSync: true gives Signal<string | undefined>. That is correct. requireSync checks that something arrived, and it does not care what the value is.
The type widens to match the initial value. If you pass initialValue: null for an observable of User, the type is User | null. If you pass a value of a different type, it is rejected by the compiler.
Subscription happens at creation. toSignal subscribes when you call it, not when something first reads the signal. This is why requireSync can check immediately. It also means that new BehaviorSubject(...) must be created before toSignal runs. In a class, field order matters:
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'app-order',
template: `<p>{{ value() }}</p>`,
})
export class Order {
// Declared first, so it exists when the next field initializer runs.
private source$ = new BehaviorSubject('ready');
value = toSignal(this.source$, { requireSync: true });
}If you swapped the two lines, this.source$ would be undefined when toSignal ran, and the call would fail.
Summary
toSignalwithout options returnsSignal<T | undefined>, because the signal has nothing to hold until the first emission.initialValuesupplies the value for that gap and removesundefinedfrom the type, unless the value you give isundefineditself.requireSync: trueremoves the gap by requiring a synchronous emission, and it throws at thetoSignalcall if none arrives.BehaviorSubject,ofandstartWithpipes are synchronous.Subject, timers, events and HTTP are not.
Exercise
A component has results = toSignal(this.http.get<string[]>('/api/items'), { requireSync: true });. What happens, and what should you change?
Show answer
HttpClient emits only after the response arrives, so nothing is emitted during subscription. toSignal throws when the component is created, at the toSignal call. Replace requireSync with initialValue, for example { initialValue: [] as string[] }, so the signal has type Signal<string[]> and starts as an empty array.
Exercise
You write toSignal(of(1, 2, 3), { requireSync: true }). What type does the signal have, and what value does it hold when read after creation?
Show answer
The type is Signal<number>. of emits 1, 2 and 3 synchronously during subscription and then completes. The signal keeps the last value, so reading it returns 3.
Exercise
You have selected$ = new Subject<string>() and want a Signal<string> that shows 'none' until the first selection. Write the toSignal call in two ways, and say which one lets other subscribers of the same observable also see 'none'.
Show answer
Option 1: toSignal(this.selected$, { initialValue: 'none' }). Option 2: toSignal(this.selected$.pipe(startWith('none')), { requireSync: true }). Only the startWith version puts 'none' into the stream itself, so other subscribers to the piped observable would also receive it. With initialValue, only the signal knows about 'none'.