Angular Web Framework RxJS & Observables 2 — Questions and Answers
Question 1: Which RxJS operator transforms each emitted value into an Observable and flattens only the most recent inner Observable, canceling previous ones?
- mergeMap
- concatMap
- switchMap (Correct answer)
- exhaustMap
Correct answer: switchMap
switchMap unsubscribes from the previous inner Observable when a new source value arrives, making it ideal for cancellable requests like autocomplete.
Question 2: What does the RxJS `catchError` operator do when the source Observable errors?
- Retries the source Observable automatically
- Returns a new Observable or rethrows the error (Correct answer)
- Completes the stream silently
- Logs the error to the console
Correct answer: Returns a new Observable or rethrows the error
catchError intercepts an error and lets you return a fallback Observable or rethrow it as a new error.
Question 3: Which Subject type in RxJS replays a specified number of past emissions to new subscribers?
- BehaviorSubject
- ReplaySubject (Correct answer)
- AsyncSubject
- PublishSubject
Correct answer: ReplaySubject
ReplaySubject buffers a configurable number of emissions and replays them to any new subscriber.
Question 4: What is the purpose of the `takeUntil` operator in Angular component lifecycle management?
- Limits emissions to a fixed count
- Completes the Observable when a notifier Observable emits (Correct answer)
- Delays subscription until a signal fires
- Filters values that arrive before a deadline
Correct answer: Completes the Observable when a notifier Observable emits
takeUntil is commonly used with a destroy$ Subject to automatically unsubscribe when a component is destroyed.
Question 5: Which RxJS creation operator converts a Promise into an Observable?
- of
- from (Correct answer)
- defer
- fromEvent
Correct answer: from
from accepts a Promise (as well as arrays and iterables) and wraps it in an Observable that emits the resolved value.
Question 6: What distinguishes a `cold` Observable from a `hot` Observable in RxJS?
- Cold Observables never complete; hot Observables always complete
- Cold Observables start producing values upon each subscription; hot Observables share a single execution (Correct answer)
- Cold Observables are synchronous; hot Observables are asynchronous
- Cold Observables require a Subject; hot Observables do not
Correct answer: Cold Observables start producing values upon each subscription; hot Observables share a single execution
Each subscriber to a cold Observable triggers an independent data producer, while hot Observables multicast from a shared source regardless of subscribers.
Question 7: Which operator combines multiple Observables and emits an array of their latest values whenever any source emits?
- zip
- forkJoin
- combineLatest (Correct answer)
- withLatestFrom
Correct answer: combineLatest
combineLatest emits a combined array of the latest values from all input Observables each time any one of them emits.