コンテンツにスキップ

withInitialValue

初期値を持たない Observable に初期値を提供します。 結果の Observable はサブスクリプション時に即座に初期値を発行し、 その後ソースからの後続の値をすべて発行します。

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