Member-only story
RxJS: Understanding Subjects
I see a lot of questions about subjects on Stack Overflow. Recently, I saw one that asked how an AsyncSubject
should be used. The question prompted me to write this article to show why the various types of subjects are necessary and how they are used in RxJS itself.
What’s the use case for subjects?
In his article On the Subject of Subjects, Ben Lesh states that:
… [multicasting] is the primary use case for Subjects in RxJS.
We’ll look at multicasting in more detail later in the article, but for now it’s enough to know that it involves taking the notifications from a single, source observable and forwarding them to one or more destination observers.
This connecting of observers to an observable is what subjects are all about. They’re able to do it because subjects themselves are both observers and observables.
How can subjects be used?
Let’s use an Angular component as an example: an awesome-component
. Our component does some awesome stuff and has an internal observable that emits values as the user interacts with the component.
To enable parent components to connect to the observable, the awesome-component
accepts an observer
input property — which it subscribes to the…