#rxjs #tutorial #advanced

Day 8: Subjects & Multicasting

Day 8: Subjects

Standard Observables are Cold and Unicast.

  • Cold: The producer is created inside the observable (e.g., a new timer starts for each subscriber).
  • Unicast: Each subscriber gets their own independent execution.

Subjects are Hot and Multicast.

  • They are both an Observable (you can subscribe to them) AND an Observer (you can call .next() on them).
  • All subscribers share the same execution.

1. Subject

A basic event emitter. Late subscribers miss old values.

import { Subject } from 'rxjs';

const subject = new Subject<number>();

subject.subscribe(v => console.log('Sub A:', v));

subject.next(1); // Sub A sees 1
subject.next(2); // Sub A sees 2

subject.subscribe(v => console.log('Sub B:', v)); // Sub B starts here

subject.next(3);
// Sub A sees 3
// Sub B sees 3

2. BehaviorSubject (Most Common)

Requires an initial value. It always stores the current value. New subscribers immediately receive the current value.

Use case: State Management (e.g., Current User, Theme).

import { BehaviorSubject } from 'rxjs';

const currentUser$ = new BehaviorSubject('Guest');

currentUser$.subscribe(console.log); // Output: "Guest"

currentUser$.next('Jack'); // Output: "Jack"

currentUser$.subscribe(console.log); // Output: "Jack" (Immediately!)

3. ReplaySubject

Stores the last n values and replays them to new subscribers.

import { ReplaySubject } from 'rxjs';

const history$ = new ReplaySubject(2); // Buffer size 2

history$.next('Page 1');
history$.next('Page 2');
history$.next('Page 3');

history$.subscribe(console.log);
// Output: "Page 2", "Page 3" (Replayed last 2)

4. AsyncSubject

Only emits the last value, and only when .complete() is called. Similar to a Promise.


Homework for Day 8:

  1. Create a BehaviorSubject with value 0.
  2. Create two buttons: “Increment” and “Log State”.
  3. “Increment” calls .next(current + 1).
  4. “Log State” subscribes to the subject and alerts the value. Notice it’s always up to date!

Day 9: Error Handling!