BACK
Lessons17. startWith: an initial value for the UI
Lessons · 17

17. startWith: an initial value for the UI

startWith — an initial value

UIs often need to show something immediately, without waiting for server data — "Loading...", an empty list, default settings. The startWith(value) operator adds an initial value at the very front of the stream.

of('Loaded').pipe(startWith('Loading'))
// next('Loading') → next('Loaded') → complete()

Where you'll see it a lot

  • Loading states: show "Loading..." until the HTTP response arrives.
  • Defaults for filters: startWith('') for a search box, startWith('all') for a category.
  • Any situation that needs an immediate value "before anything has happened."

Your task

  1. Inside pipe, add startWith('Loading').
  2. Expected output: State: Loading → State: Loaded. The first value shows instantly; the second comes from the source.
Solution spoiler · click to reveal
const { of, startWith } = Rx;

const state$ = of('Loaded').pipe(
  startWith('Loading')
);

state$.subscribe(value => {
  console.log('State: ' + value);
});
script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...