Question presented to candidate: "We keep the logged-in user in a service and several components subscribe to it, some of them long after login. Which kind of Subject would you use, and how do Subject, BehaviorSubject and ReplaySubject differ?"
What a strong answer should cover:
- A Subject is both an Observable and an Observer: it multicasts each
next()to every current subscriber, and is hot (values sent before you subscribe are gone). - The three differ in what a late subscriber receives: Subject gives nothing from the past, BehaviorSubject gives the current value (it needs an initial one), ReplaySubject(n) replays the last n values (optionally limited by a time window).
- BehaviorSubject exposes a synchronous
getValue()/value; ReplaySubject has no initial value and no getter. - After
complete()a late subscriber of a BehaviorSubject gets only the completion, while a ReplaySubject still replays its buffer. - Expose subjects with
asObservable()so only the owning service can callnext(); in modern Angular asignal()often replaces a BehaviorSubject for UI state. - Mention AsyncSubject (emits only the last value, on complete) as the fourth variant.
Clarifying questions expected:
- "Does a component that subscribes later need the current value, or only future changes?"
- "Is this UI state the template reads (a signal might fit better) or an event stream?"
Code / implementation expected: Yes β a small service or component that shows what a late subscriber gets from each subject.