When do you use BehaviorSubject?
Answer
Use a BehaviorSubject when subscribers need the current value immediately, such as a small state store. It requires an initial value and exposes the latest value, so avoid it for one-off event streams.
Context
RxJS models asynchronous values as composable streams. The important design choice is the source lifetime and concurrency rule: cancel, merge, queue, or ignore competing work deliberately.
Example
ts
const results$ = query$.pipe(
debounceTime(250),
distinctUntilChanged(),
switchMap(query => api.search(query))
)switchMap ensures an older search result cannot overwrite a newer query.
Practical considerations
- Choose the approach from the requirement and constraints, not from habit.
- Include validation, error handling, and cleanup where the boundary requires them.
- Verify the observable result with focused tests or measurement.
Follow-up prompts
- What failure mode would you expect if this were implemented incorrectly?
- How would you test this behaviour?
- What changes when the feature must scale to a larger application or team?
In practice
For this medium-level topic, make assumptions explicit, choose the smallest safe implementation, and verify the behavior at the relevant boundary.