What are Subject, BehaviorSubject and ReplaySubject, and when would you use each?
Model answer
A Subject is both an Observable and an observer: you can call next() on it and many subscribers receive the values. BehaviorSubject needs an initial value, keeps the latest one and gives it to new subscribers immediately, which suits "current state" such as the logged-in user. ReplaySubject remembers a set number of past values for late subscribers.
Expose them to other classes as read-only Observables (asObservable()) so only the owner can call next(). For simple state, signals are often easier now.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- How do you call an API in Angular?
- What is an Observable, and how is it different from a Promise?
- What is the difference between subscribe and the async pipe?
- What are common RxJS operators you use, and what do they do?
- Explain the difference between switchMap, mergeMap, concatMap and exhaustMap.
- What are HTTP interceptors, and what are they used for?