Subject
Goals
- Learn how the Subject is both an Observable and an Observer.
- Recap what an Observer is.
- Learn the difference between Unicast and Multicast.
- Learn that Observables are Unicast by default.
- Learn that Subjects are Multicast.
- Practice using a `Subject`.
What is a Subject?
- The
Subject
class extends theObservable
class. This means that you can use Subjects the same way you are used to using Observables. You cansubscribe()
to notifications and you can use operators within thepipe()
. - A
Subject
is both an Observable and an Observer. In other words, Subjects enable us to both emit notifications and listen for notifications. - Subjects multicast. We'll learn more about this later.
Why do we have a Subject?
When we need to create an Observable where we can emit notifications from outside of the subscribe function.
Variations
The Subject
class extends the Observable
class, and in turn, there are several subclasses of the Subject
:
BehaviorSubject
AsyncSubject
ReplaySubject
WebSocketSubject
Each variation behaves differently in how notifications are emitted and the timing of those notifications.
Creation
New-up a Subject()
via:
const users = new Subject();
If we are using TypeScript, then we can also specify the generic type. The class signature is:
class Subject<T> extends Observable<T> implements SubscriptionLike {}
- Here we see that the
Subject
class extends theObservable
class. - The class also implements the
SubscriptionLike
interface which requires anunsubscribe()
method.
Using TypeScript we specify the generic as follows:
const users = new Subject<User[]>();
In this example, the type for the next notification is an array of User
objects.