Observable
- Unicast → Each subscription creates a new execution.
- Example: If 3 subscribers subscribe to the same Observable, each gets its own independent execution of data.
- Useful for streams like HTTP calls (each subscriber triggers a new request).
import { Observable } from 'rxjs';
const obs = new Observable(observer => {
observer.next(Math.random()); // emits random number
});
obs.subscribe(val => console.log('Subscriber 1:', val));
obs.subscribe(val => console.log('Subscriber 2:', val));
Each subscriber will get a different random number.
Subject
- Multicast → A single execution is shared among all subscribers.
- Behaves like an Observable (subscribers can listen) and an Observer (can emit data).
- All subscribers receive the same emitted value.
import { Subject } from 'rxjs';
const subject = new Subject<number>();
subject.subscribe(val => console.log('Subscriber 1:', val));
subject.subscribe(val => console.log('Subscriber 2:', val));
subject.next(Math.random()); // both subscribers get the same value
Both subscribers get the same random number.
ReplaySubject
- Records a buffer of emitted values and replays them to new subscribers.
- You define buffer size (how many previous values to replay).
import { ReplaySubject } from 'rxjs';
const rSubject = new ReplaySubject<number>(2); // buffer size = 2
rSubject.next(1);
rSubject.next(2);
rSubject.next(3);
rSubject.subscribe(val => console.log('Subscriber:', val));
// gets 2, 3 (last 2 values)
Use case: Chat history, logs, caching previous values.
AsyncSubject
- Emits only the last value when the subject completes.
- All subscribers get the same single value.
import { AsyncSubject } from 'rxjs';
const aSubject = new AsyncSubject<number>();
aSubject.subscribe(val => console.log('Subscriber 1:', val));
aSubject.next(1);
aSubject.next(2);
aSubject.next(3);
aSubject.complete(); // Only last value (3) is sent to subscribers
Use case: When you only care about the final result (e.g., API completion, calculation result).
Multicasting & State Sharing
- Multicasting = One producer, many consumers.
- Without Subjects → Each subscriber gets its own execution.
- With Subjects → Same execution shared.
Example with shareReplay (RxJS operator, internally uses a ReplaySubject):
import { of } from 'rxjs';
import { shareReplay, delay } from 'rxjs/operators';
const source$ = of(Math.random()).pipe(
source$.subscribe(val => console.log('Subscriber 1:', val));
source$.subscribe(val => console.log('Subscriber 2:', val));
Both subscribers get the same cached random number.
Cross-Component Communication
Scenario
You want Component A to send data to Component B without using Input/Output or parent-child relation.
Use a Shared Service with a Subject.
Go and check git reposotory check all the example properly.

Comments
Post a Comment