Understanding Subject in Angular

A subject can act as an observable and observer too and is present in ‘rxjs’ library. Unlike observable it allows values to be multicasted to many observers. Let’s see a diagram to understand it.

In the above diagram, as the next(“first”) call takes place, it feeds a new value to the subject. The observers which are currently registered to it get this value. Hence the value is multicasted to the various observers.
Let’s see what will happen if a new observer is registered after these three already registered observers.

Now a new observer is registered. And next(“new”) call feeds a value to the subject and it multicasts the “new” value to all the observers. The important point is “The new observer does not get the old value as it is registered later”.
Some points after seeing both the above diagram is :
- A subject does not have an initial value. Value is fed to the subject only after the next() call.
- Subjects unlike observable can multicast values to the many observers.
- Subjects do not emit the last value to the new observers added.
Let’s now see how to create a subject and make its little demo.

In the above, I just imported the subject from ‘rxjs’. Took a variable and you can see how easy it is to create a subject.
Pat your back and take a sip of coffee.☕
Done !??😁
The next step is to create a function addItem within your class.

Next, create an observer and call the next().

Let’s make some changes in the HTML and see the result.

Ignore the styling but did you get the result like below? If ‘YES’,kudoooos you did it.🎊🎊

Now, experiment by adding one more observer.

Let’s now view the output. Did you see something like below (ignore the style)?

After seeing the above results, recall the points we discussed above.
Kudos, you learnt about the subject in angular.
Thank you ✨✨
Happy Coding !!