Blog4 min read

RxJS Interview Questions and Answers

On this page23 sections

RxJS Interview Questions and Answers

RxJS questions come up in Angular interviews and anywhere a team models events as streams. Interviewers usually start with “Observable vs Promise” and move quickly to operators, because choosing between switchMap, mergeMap and concatMap is where real bugs come from. These 18 questions follow that path.

Fundamentals

1. What is an Observable?

A lazy stream of values over time. It can emit zero, one or many values, then complete or error. Nothing happens until something subscribes.

import { Observable } from 'rxjs';

const ticks$ = new Observable<number>((subscriber) => {
  let n = 0;
  const id = setInterval(() => subscriber.next(n++), 1000);
  return () => clearInterval(id); // teardown runs on unsubscribe
});

const sub = ticks$.subscribe((n) => console.log(n));
sub.unsubscribe();

2. Observable vs Promise?

Promise Observable
Values One Zero to many
Starts Immediately (eager) On subscribe (lazy)
Cancellable No Yes: unsubscribe()
Operators then, catch map, filter, debounceTime, and many more
Retry Call the function again Resubscribe: retry()

3. What does the $ suffix mean?

A naming convention for variables that hold an Observable: user$, clicks$.

4. Cold vs hot Observables?

  • Cold: each subscriber gets its own execution. An HTTP Observable sends a new request per subscriber.
  • Hot: the source runs regardless and subscribers share it. Mouse events and WebSocket messages are hot.

Make a cold Observable shared with share() or shareReplay().

5. What are Subjects, and how do the types differ?

A Subject is both an Observable and an observer: you can call next() on it, and it multicasts to all subscribers.

Type New subscriber receives
Subject Only values emitted after subscribing
BehaviorSubject(initial) The current value immediately, then updates
ReplaySubject(n) The last n values, then updates
AsyncSubject Only the final value, when the source completes

BehaviorSubject is the usual choice for state.

6. How do you implement an Observable from scratch?

A favourite coding question. The core is a class that stores a subscribe function and returns an unsubscribe handle. Work through it in build an Observable.

Operators

7. map vs tap?

map transforms each value. tap runs a side effect (logging, analytics) and passes the value through unchanged.

8. switchMap vs mergeMap vs concatMap vs exhaustMap?

All four map each value to an inner Observable. They differ in what happens when a new value arrives while the previous inner Observable is still running.

Operator Behaviour Use for
switchMap Cancels the previous one Search, route params: only the latest matters
mergeMap Runs all in parallel Independent requests where order doesn’t matter
concatMap Queues, runs one at a time in order Saves that must apply in sequence
exhaustMap Ignores new values until the current one finishes Login or submit buttons: prevent double submits

Using switchMap for a save can cancel a write in progress. Using mergeMap for search lets an old response overwrite a newer one.

import { catchError, debounceTime, distinctUntilChanged, filter, fromEvent, map, of, switchMap } from 'rxjs';

const results$ = fromEvent<InputEvent>(input, 'input').pipe(
  map((e) => (e.target as HTMLInputElement).value.trim()),
  debounceTime(300),          // wait for a pause in typing
  distinctUntilChanged(),     // skip if the text didn't change
  filter((q) => q.length >= 2),
  switchMap((q) =>
    search(q).pipe(catchError(() => of([]))) // keep the stream alive on error
  )
);

Each line answers a follow-up: fewer requests, no duplicate queries, no stale responses, and one failed request doesn’t end the stream. Compare with the plain JavaScript version in autocomplete search.

10. combineLatest vs forkJoin vs zip vs withLatestFrom?

Operator Emits
combineLatest Whenever any source emits, once all have emitted at least once
forkJoin Once, with the last value of each, when all complete (like Promise.all)
zip Pairs by index: first with first, second with second
withLatestFrom When the main source emits, with the latest from the others

11. debounceTime vs throttleTime vs auditTime?

debounceTime emits after a quiet period. throttleTime emits the first value, then ignores the rest for the window. auditTime ignores for the window, then emits the most recent value.

12. take, first, takeUntil, takeWhile?

take(n) completes after n values. first() is take(1) but errors on an empty stream. takeUntil(notifier$) completes when another Observable emits. takeWhile(fn) completes when the predicate fails.

Errors and resources

13. How does error handling work?

An error ends the stream. catchError replaces it with another Observable; retry resubscribes to the source.

data$.pipe(
  retry({ count: 3, delay: 1000 }),
  catchError((err) => {
    report(err);
    return of(fallback);
  })
);

Place catchError inside the inner Observable of a switchMap (as in question 9). On the outer stream it would end the whole pipeline after the first failure.

14. How do subscriptions leak, and how do you prevent it?

A subscription to a long-lived source (an interval, a Subject in a service, DOM events) keeps running after the component is gone. Options:

  • Angular’s async pipe, which subscribes and unsubscribes for you.
  • takeUntilDestroyed() in Angular, or takeUntil(destroy$) elsewhere.
  • Store the Subscription and call unsubscribe() in cleanup.

HTTP Observables complete on their own, but unsubscribing still cancels the in-flight request.

15. share vs shareReplay?

share() multicasts to current subscribers. shareReplay({ bufferSize: 1, refCount: true }) also replays the last value to late subscribers, which makes it a simple cache for an HTTP call. Without refCount: true, the source subscription stays alive after everyone unsubscribes.

16. How do you convert between Promises and Observables?

from(promise) or defer(() => promise) to go in. firstValueFrom(obs$) and lastValueFrom(obs$) to come out. toPromise() is deprecated.

Design

17. What are schedulers?

They control when work runs: asyncScheduler (timers), asapScheduler (microtasks), animationFrameScheduler (before paint). Most code never names one, but observeOn(animationFrameScheduler) is useful for smooth visual updates.

18. When would you not use RxJS?

For a single request and response, async/await is simpler. RxJS earns its place when you combine several event sources, need cancellation, or have timing logic such as debouncing, retries and polling. In Angular, signals now cover a lot of synchronous state, with RxJS kept for asynchronous streams.

How to practise

Implement an Observable with map and filter, then build the typeahead from question 9 and explain each operator aloud. For Angular roles, continue with Angular interview questions.