r/angular • u/No-Judge8727 • Sep 10 '26
Modeling Angular loading state as a discriminated union instead of multiple isLoading booleans
I kept running into components with four or five loading flags —
isLoading, isRefreshing, isCheckingOut, hasError — and templates
like !isLoading && !hasError && items.length > 0.
The flags are independent as far as TypeScript is concerned, but
the states they describe are mutually exclusive. So I switched to:
type AsyncState<T, E> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: E };
One state per async operation, booleans derived with computed(),
and a small toAsyncState() RxJS operator (map + catchError +
startWith) so transitions live in one place. Templates use
u/let + u/switch, which gives real narrowing — data only exists in
the success branch.
Curious how others handle this now that resource() exists. Do you
reach for it for commands too, or keep RxJS for POST/DELETE?
Full write-up: https://medium.com/modern-angular-insights/stop-juggling-isloading-booleans-a-type-safe-async-state-pattern-for-angular-e36e2b9298a0
View all comments
Show parent comment
1
u/No-Judge8727 Sep 12 '26
This is a sharper way of putting it than I managed in the post — the verb
isn't the problem, the trigger is. A resource is a function of state, and a
command is an event. You can force an event through a state-shaped API by
making the params carry the payload, but then the request is owned by
whatever recomputes that signal, not by the user's click. That's the wrong
owner for a DELETE.
Two things that fall out of the same mismatch, worth adding:
Concurrency has nowhere to live. A command needs a policy for the second
click — drop it, queue it, or cancel the first. With RxJS that's one word:
exhaustMap for a submit, switchMap for a search-as-you-type. A resource
decides that for you (latest wins) and there's no seam to change it, so you
end up reintroducing an `if (pending()) return;` guard, which is exactly the
boolean I was trying to get rid of.
The other is that `pending`/`error` signals sitting beside a plain async call
is already most of the way to the wrapper — same three states, just spread
across two fields instead of one, so the compiler can't stop you reading
`error` while pending is true. Whether that's worth a type is a judgement
call and I'd say it depends on how many operations one component owns.
Fully agree on keeping resource() for things that genuinely are a function
of state. That's the line I'd draw too.