RxJs Subjects: When and why?

Our RxJs topic for this week is going to be Subjects. Angular has multiple services and classes (such as FormControl) that give us access to Observables that we can subscribe to. But what if we want to create our own Observable to emit data?

While there is an Observable constructor and Observable creation functions such as of and from, none of these solutions are as powerful and feature-complete as using a Subject.

Why is that? Because Subjects check a lot of boxes for us:

  • They are multicast, which means they support multiple subscribers out of the box (an Observable does not by default)
  • They can replay values to new subscribers (BehaviorSubject and ReplaySubject do that)

Those two features are critical when building Angular apps because our data is usually handled by services, then consumed by components. For example, suppose a service fetches some data (say, the user session info upon login). In that case, it is essential for components that will be displayed later on the screen to subscribe to that information and get the current session info right away (that’s why replayability/caching the latest value is critical).

As a plus, the Subject API is incredibly straightforward:

So we have complete control over what we emit, when, and how. All with a single method: .next()

And since a Subject is a specific type of Observable, you can subscribe to it the same way: subject.subscribe(). That said, it is a best practice to expose the subject as an Observable by using the asObservable() method as illustrated here:

For more details on how to use Subjects and what are the different types of Subjects, feel free to head to my RxJs subjects tutorial.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.