Lessons38. Subject: a hot multicast stream
Lessons · 38
38. Subject: a hot multicast stream
Subject — a stream you can "push" into
So far we've only subscribed to Observables. But sometimes you need to send values from the outside: events from a component, user actions, an EventEmitter. That's what a Subject is for.
A Subject is, at the same time:
- An Observable — you can subscribe to it.
- An Observer — it has a
.next(value)method anyone can use to "push" values.
Multicast (one source — many subscribers)
Unlike a cold Observable, which runs its logic separately for each subscriber, a Subject acts like a "hub": every subscriber gets the very same values. That's what multicast means.
No memory
A plain Subject remembers nothing. A new subscriber hears only what happens after it subscribes. Past values are lost to it. This matters — in the next lessons we'll study BehaviorSubject and ReplaySubject, which fix exactly that.
Your task
- Create a Subject:
const subject = new Subject(); - Below the first subscription, call
subject.next(1). - Below the second subscription, call
subject.next(2). - Expected output:
Sub A: 1 → Sub A: 2 → Sub B: 2. Sub B never heard1— it subscribed later.
Solution spoiler · click to reveal
const { Subject } = Rx;
const subject = new Subject();
subject.subscribe(value => console.log('Sub A: ' + value));
subject.next(1);
subject.subscribe(value => console.log('Sub B: ' + value));
subject.next(2); script.ts
CONSOLE · Console output
Hit Run to see the result...