Skip to content

withInitialValue

Provides an initial value for an observable that doesn’t have one. The resulting observable will immediately emit the initial value upon subscription, and then emit all subsequent values from the source.

Timeline of observable events123
withInitialValue(0)
Timeline of observable events0123
// Timeline:
//
// num$ 1 2 3
// withInitial$ 0 1 2 3
// ^
// initial value
//
// Explanation:
// - withInitialValue provides an initial value before the source emits
// - Converts an uninitialized observable to an initialized one
// - Useful when you need a default value immediately
const num$ = source<number>();
const initialized$ = num$.pipe(withInitialValue(0));
const valueHistory: number[] = [];
initialized$.subscribe((x) => {
valueHistory.push(x);
});
assert.deepStrictEqual(valueHistory, [0]);
num$.next(1); // logs: 1
assert.deepStrictEqual(valueHistory, [0, 1]);
num$.next(2); // logs: 2
assert.deepStrictEqual(valueHistory, [0, 1, 2]);

View source on GitHub