MyInternships.in

RxJS & Reactive Programming

Angular Subject and BehaviorSubject

A Subject is both an Observable and an observer: you can subscribe to it and also push values into it with next(). BehaviorSubject additionally stores the current value and replays it to every new subscriber.


What is Subject and BehaviorSubject in Angular?

A Subject is both an Observable and an observer: you can subscribe to it and also push values into it with next(). BehaviorSubject additionally stores the current value and replays it to every new subscriber.

Subject and BehaviorSubject example

A state service built on BehaviorSubject
TypeScript
@Injectable({ providedIn: 'root' })
export class CartService {
  private itemsSubject = new BehaviorSubject<Job[]>([]);
  items$ = this.itemsSubject.asObservable();

  get items(): Job[] { return this.itemsSubject.value; }

  add(job: Job): void {
    this.itemsSubject.next([...this.items, job]);
  }
}

Key points to remember

  • BehaviorSubject for current state; Subject for one-off events.
  • Expose it with asObservable() so consumers cannot push values.
  • Signals now cover many BehaviorSubject use cases with less ceremony.

Subject variants

TypeReplaysNeeds an initial value
Subjectnothingno
BehaviorSubjectthe latest valueyes
ReplaySubject(n)the last n valuesno
AsyncSubjectthe final value, on completeno

Common mistakes with Subject and BehaviorSubject

  • Using Subject for state and finding that late subscribers see nothing.
  • Reading .value everywhere instead of subscribing, which loses reactivity.

Angular Subject and BehaviorSubject— Interview Questions & FAQs

What is the difference between Subject and BehaviorSubject?+

A Subject emits only to subscribers present at the time of emission. A BehaviorSubject holds the most recent value and immediately replays it to every new subscriber, which is what makes it suitable for state.

Related Angular Topics

Keep learning with these closely related lessons.

Ready to use your Angular skills?

Find verified Angular internships and fresher developer jobs across India.

Browse Angular Internships