BACK
Use casesManual refresh — a refresh button + initial load
Use cases · 26

Manual refresh — a refresh button + initial load

Pattern

A page loads data on open, and it has a "Refresh" button. The logic is the same: "load the data." We don't want to duplicate the HTTP code in two places.

The problem it solves

Split the logic into initial-load (in ngOnInit) and refresh-click (in a button handler) and sooner or later they diverge. One fixes the loading state, the other doesn't. One adds retry, the other forgets. Code drift.

Operators and why they matter

  • Subject — models the Refresh button.
  • startWith('initial') — adds the first trigger automatically, with no separate method call. Initial load and refresh are the same stream.
  • switchMap — if the user hits the button while a response is in flight, cancel the old request and load again.
  • map — builds the VM for the template.

Gotchas

  • mergeMap — two parallel refreshes; responses may arrive out of order. The UI flickers with old data.
  • concatMap — every click queues up. Press it 5 times and you get 5 sequential requests, though only the last is needed.
  • Without startWith, the page is empty until the first click. The initial load never fires.

What you get

One pipeline covers the first load and manual refresh with identical rules. DRY without any wizardry.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...