Question presented to candidate:
"Angular's HttpClient returns an Observable, while fetch returns a Promise. What is actually different between the two, and why did Angular choose Observables?"
What a strong answer should cover:
- Eager vs lazy: a Promise starts its work when it is created; an Observable does nothing until it is subscribed, and runs again for every subscriber (cold).
- One value vs many: a Promise settles once (later
resolvecalls are ignored); an Observable can emit zero, one or many values, then complete or error. - Timing:
thencallbacks are always asynchronous (microtasks); an Observable can emit synchronously duringsubscribe(). - Cancellation: unsubscribing runs the producer's teardown (clears timers, aborts requests); a Promise cannot be cancelled.
- Operators: RxJS gives
map,switchMap,retry,debounceTime, combination; Promises havethen,Promise.all/race/allSettled/any. - Conversion:
from(promise),defer(() => promise)for laziness,firstValueFrom/lastValueFromback (withEmptyErroron an empty stream).
Clarifying questions expected:
- "Do you want the conceptual comparison, or how it affects HttpClient code in components?"
- "Is the team mixing
async/awaitwith Observables today?"
Code / implementation expected: Optional β a small snippet showing eager vs lazy execution and cancelling a stream.