Before we start, this article requires basic knowledge in Rx.

Let’s say we have two observables:

Every time we call subscribe with new observer we are creating a new execution. You can think of it as a normal function that executes twice. For example:

We are creating two intervals that are independent of each other. But what if we need the second observer to get the same events has the first?

This is the case when you are going to need to use Subject in Rx.

What are Subjects?

Subject is both an observable and observer.

Observer — it has the next, error, and complete methods. Observable — it has all the observable operators, and you can subscribe to him.

A subject can act as a bridge/proxy between the source observable and many observers, making it possible for multiple observers to share the same observable execution.

Let’s see how we can share the same execution in our first example:

First, we are creating a new Subject. Now, remember that a subject is also an observer, and what observers can do? They can listen to observables with the next() , error() and complete() methods. If you log the subject, you can see that the subject has these methods.

So in our case, the subject is observing the interval observable. In simple words when you have new values let me know.

Now let’s move on to the next part.

A subject is also observable, and what we can do with observables? We can subscribe to them.

In our case, we are subscribing to the subject. But what values the subject gives us?

If you remember the subject is observing the interval observable, so every time the interval send values to the subject, the subject send this values to all his observers.

The subject acts as a proxy/bridge, and because of that, there is only one execution.

Oh, I got new value from the interval observable, I am passing this value to all my observers (listeners)

Don’t forget that every subject is also an observer so we can use the observer methods next() , error() , complete() . Let’s see an example:

We can subscribe to the subject, and we can manually trigger the next() method. When you call the next() method every subscriber will get this value. (you can also trigger error() and complete() )

We learned about the simplest subject in Rx. More types of subjects can solve more complex situations, BehaviorSubject , AsyncSubject , and ReplaySubject .

The most common one is the BehaviorSubject , and you can read about him in my latest article.

Things to not miss:

Follow me on Medium or Twitter to read more about Angular, Vue and JS!