Thuta Learning
Angular
AdvancedWeb DevelopmentIntermediate

Subject & BehaviorSubject

AngularLesson 3025 min

What you'll walk away with

  • Explain the core concept and Angular data flow of Subject & BehaviorSubject
  • Run the example, predict its state and UI, and test edge and error cases
  • Apply a typed safe pattern in a real project and recognize common pitfalls

Explain it simply

Subject & BehaviorSubject, in plain language

Subject is both an Observable and an Observer. BehaviorSubject stores its current value and immediately hands it to new subscribers.

Problem → Why → Solution

The problem — why this concept matters

Exposing a public Subject that every component can next into removes control over state transitions.

A common mistake

One happy-path result does not prove the feature works; empty, loading, error, and cleanup behavior need explicit tests.

Core concept — understand how it works

A Subject is both an Observable and an Observer and multicasts values to multiple subscribers. BehaviorSubject retains a current value and immediately emits it to new subscribers, which is useful for state, but write access should remain private while consumers receive a readonly stream or signal. Choose subject types according to replay, completion, and initial-state semantics.

Mental model
  1. input and state
  2. component and template
  3. rendered Angular UI

Explain the core concept and Angular data flow of Subject & BehaviorSubject

Core syntax or pattern

typescript
import { Subject, BehaviorSubject } from 'rxjs';

// Subject - simple event bus
const subject = new Subject<string>();

subject.subscribe(val => console.log('Subscriber 1:', val));
subject.next('Hello');  // Subscriber 1: Hello

subject.subscribe(val => console.log('Subscriber 2:', val));
subject.next('World');  // Both subscribers receive 'World'

// BehaviorSubject - has initial value, remembers last value
const behaviorSubject = new BehaviorSubject<number>(0);

behaviorSubject.subscribe(val => console.log('Sub A:', val));  // Sub A: 0
behaviorSubject.next(1);  // Sub A: 1

// New subscriber gets last value immediately
behaviorSubject.subscribe(val => console.log('Sub B:', val));  // Sub B: 1

// Real example: Shared state service
@Injectable({ providedIn: 'root' })
export class UserStateService {
  private userSubject = new BehaviorSubject<User | null>(null);
  user$ = this.userSubject.asObservable();
  
  setUser(user: User) {
    this.userSubject.next(user);
  }
}

A Subject is both an Observable and an Observer and multicasts values to multiple subscribers. BehaviorSubject retains a current value and immediately emits it to new subscribers, which is useful for state, but write access should remain private while consumers receive a readonly stream or signal. Choose subject types according to replay, completion, and initial-state semantics.

Read the code step by step

  1. input and stateimport { Subject, BehaviorSubject } from 'rxjs';

    Subject is both an Observable and an Observer. BehaviorSubject stores its current value and immediately hands it to new subscribers.

  2. component and template// New subscriber gets last value immediately

    A Subject is both an Observable and an Observer and multicasts values to multiple subscribers. BehaviorSubject retains a current value and immediately emits it to new subscribers, which is useful for state, but write access should remain private while consumers receive a readonly stream or signal. Choose subject types according to replay, completion, and initial-state semantics.

  3. rendered Angular UI}

    Build a cart service with a private BehaviorSubject and immutable update methods, verifying two components observe the shared total.

Execution flow
  1. input and state
  2. component and template
  3. rendered Angular UI

Success

Explain the core concept and Angular data flow of Subject & BehaviorSubject

Failure

Exposing a public Subject that every component can next into removes control over state transitions.

Subject is both an Observable and an Observer. BehaviorSubject stores its current value and immediately hands it to new subscribers.

typescript
import { Subject, BehaviorSubject } from 'rxjs';

// Subject - simple event bus
const subject = new Subject<string>();

subject.subscribe(val => console.log('Subscriber 1:', val));
subject.next('Hello');  // Subscriber 1: Hello

subject.subscribe(val => console.log('Subscriber 2:', val));
subject.next('World');  // Both subscribers receive 'World'

// BehaviorSubject - has initial value, remembers last value
const behaviorSubject = new BehaviorSubject<number>(0);

behaviorSubject.subscribe(val => console.log('Sub A:', val));  // Sub A: 0
behaviorSubject.next(1);  // Sub A: 1

// New subscriber gets last value immediately
behaviorSubject.subscribe(val => console.log('Sub B:', val));  // Sub B: 1

// Real example: Shared state service
@Injectable({ providedIn: 'root' })
export class UserStateService {
  private userSubject = new BehaviorSubject<User | null>(null);
  user$ = this.userSubject.asObservable();
  
  setUser(user: User) {
    this.userSubject.next(user);
  }
}
You should see
(Subject/BehaviorSubject can be used to share data between components)

Real-world usage

How to apply it in a real project

Build a cart service with a private BehaviorSubject and immutable update methods, verifying two components observe the shared total.

Mini challenge

Build it yourself

Rebuild the Subject & BehaviorSubject example without copying it. Add two normal states, one edge case, and one failure state, and write the expected UI and state transition before running it.

  • Rebuild the example without copying it
  • Test a normal input and an edge case
  • Predict the compiler or output result before running it
typescript
import { Subject, BehaviorSubject } from 'rxjs';

// Subject - simple event bus
const subject = new Subject<string>();

subject.subscribe(val => console.log('Subscriber 1:', val));
subject.next('Hello');  // Subscriber 1: Hello

subject.subscribe(val => console.log('Subscriber 2:', val));
subject.next('World');  // Both subscribers receive 'World'

// BehaviorSubject - has initial value, remembers last value
const behaviorSubject = new BehaviorSubject<number>(0);

behaviorSubject.subscribe(val => console.log('Sub A:', val));  // Sub A: 0
behaviorSubject.next(1);  // Sub A: 1

// New subscriber gets last value immediately
behaviorSubject.subscribe(val => console.log('Sub B:', val));  // Sub B: 1

// Real example: Shared state service
@Injectable({ providedIn: 'root' })
export class UserStateService {
  private userSubject = new BehaviorSubject<User | null>(null);
  user$ = this.userSubject.asObservable();
  
  setUser(user: User) {
    this.userSubject.next(user);
  }
}

Expected: Explain the core concept and Angular data flow of Subject & BehaviorSubject

Show hint

Build a cart service with a private BehaviorSubject and immutable update methods, verifying two components observe the shared total.

Quick quiz 1 / 3

What best describes the core idea of Subject & BehaviorSubject?

Quick quiz 2 / 3

Which mistake should you avoid first?

Quick quiz 3 / 3

How should this be applied in a real project?

What to remember

  • input and state → component and template → rendered Angular UI
  • A Subject is both an Observable and an Observer and multicasts values to multiple subscribers. BehaviorSubject retains a current value and immediately emits it to new subscribers, which is useful for state, but write access should remain private while consumers receive a readonly stream or signal. Choose subject types according to replay, completion, and initial-state semantics.
  • Exposing a public Subject that every component can next into removes control over state transitions.
  • Build a cart service with a private BehaviorSubject and immutable update methods, verifying two components observe the shared total.

RxJS — Guide — RxJS

Easy traps

  • Exposing a public Subject that every component can next into removes control over state transitions.
  • One happy-path result does not prove the feature works; empty, loading, error, and cleanup behavior need explicit tests.

Hands-on Exercise

Rebuild the Subject & BehaviorSubject example without copying it. Add two normal states, one edge case, and one failure state, and write the expected UI and state transition before running it.

You'll know it worked when: (Subject/BehaviorSubject can be used to share data between components)

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Subject & BehaviorSubject | Thuta Learning