58. Introduction to Subjects (Multicasting)
Standard Observables are unicast (or 'cold'): each subscriber gets its own independent execution of the Observable logic (e.g., each HTTP subscriber triggers a new request).
Subjects are a special type of Observable that are multicast (or 'hot'): they allow multiple Observers to subscribe to the same execution. A Subject is both an Observer (it can receive values via next()) and an Observable (it can be subscribed to).
Basic Subject (Subject<T>)
A basic Subject is a stream that doesn't hold state. It only emits values to subscribers that are currently listening after the value is emitted.
Use Case: Event emitters in services for non-related component communication (replacing Angular's EventEmitter in services).
typescript import { Subject } from 'rxjs';
const statusUpdate$ = new Subject
// Subscriber A starts listening statusUpdate$.subscribe(message => console.log('Sub A:', message));
// The stream emits a value statusUpdate$.next('System Initialized'); // Output: Sub A: System Initialized
// Subscriber B starts listening later statusUpdate$.subscribe(message => console.log('Sub B:', message));
statusUpdate$.next('User logged in'); /* Output: Sub A: User logged in Sub B: User logged in */
statusUpdate$.complete(); // Terminates the stream for all subscribers
Crucially: If Subscriber B had subscribed after 'System Initialized' was emitted, it would have missed that message. The next lesson introduces Subjects that store state.