Observable Subject
Learn how to create a custom event bus using RxJS Subject, which allows multiple subscribers and the ability to notify all interested subscribers when an event occurs.
We'll cover the following
Working with Observable streams
Thus far, we have worked with Observables that emit values and have seen how to subscribe to Observable streams. The Observable itself is responsible for emitting values, and the subscribers react to values being emitted. When an Observable stream is complete, all subscribers complete their processing and their execution stops. In essence, subscribers are alive as long as the Observable stream is emitting values.
Multicasting with the Subject
class
So, what if we want to keep an Observable stream open and register one or more
subscribers that will wait around until a new value is emitted? Think in terms of an event bus, where multiple subscribers register their interest in a topic on an event bus and then react when an event is raised that they are interested in. RxJS provides the Subject
class for this express purpose.
A Subject
maintains a list of listeners that have registered their interest. A Subject
is also an Observable stream, and therefore, listeners can subscribe to the stream and use the same syntax and functions that are used for normal Observable streams.
What makes a Subject
interesting is that it has the ability to multicast, which means that it allows multiple subscribers to the same stream and will notify all interested subscribers when an event happens.
To illustrate this behavior, let’s build a minimal event bus using a Subject
.
To start with, let’s define an interface for a broadcast event as follows:
Get hands-on with 1400+ tech skills courses.