Observables are mainly the functions that allow us to pass messages inside our application. They can be thought of as an upgrade version of the simple promises. However, we also have subjects in the react programming that are a particular case of Observables. We will discuss different subjects in this article. So, let us get started.
The most significant difference between subject and observable is the casting properties.
A simple observable is a unicast, i.e., it can cast to a single observer only. In contrast, Subjects are a special kind of observables that enable us to send data to multiple components or services. It has the power to multicast many observes, which makes a subject an observer and an observable at the same time. It is noted that subjects do not possess any initial value, and they behave like event emitters.
The code below explains the working of Subjects.
A behavior subject is a type of subject that can be initialised with a value, and it will print the initial value even if it has not received a next().
Moreover, Behavior Subjects keep track of the last values, and whenever there is a new subscriber, it will get the previous value, and log it.
This can be seen in the code below.
The Behavior Subject has 0 value at the start, and when observer 1 subscribes to it, it will log it. We can see observer 2 subscribe after the value 2, but it still logs it.
This shows the tracking of the last value by Behavior Subject.
It works similar to Behavior Subject expect that it can keep track of multiple previous values and reply to them for the new subscribers. Furthermore, you can also specify the window for tracking the older values.
Let us see Reply Subject’s working.
As you can see, observer 2 gets 3 previous values after subscribing, as set during Replay Subject's initialization.
We have seen Subject, Behavior Subject, and Reply Subject in this article, each having its use case.
- Subjects are mainly used for multicasting the data.
- Behavior Subjects gets an initializing value and keeps track of the last value.
- Reply Subjects can maintain a buffer of values and pass them to new subscribers.
Thanks for reading, and see you on next articles.