In this blog, let’s learn about Rxjs Subjects and BehaviorSubject in angular.
The Rxjs Subject and BehaviorSubject are unique observables that act as both observers and observables. They allow us to emit new values to the observable stream using the
next method. All the subscribers, who subscribe to the subject will receive the same instance of the subject and hence the same values.
We will also show the difference between observable and subject. If you are new to observable then refer to this tutorial on what is observable in angular.
What are the Subjects?
A Subject is a particular type of Observable that allows values to be multicasted to many Observers. The subjects are also observers because they can subscribe to another observable and get value from it, which will be multicast to all its subscribers.
How do Subjects work
Subjects implement both
subscribe method and
complete methods. It also maintains a collection of
- Step 1: Create a service using the command
ng generate serviceor ng g s and declare a subject there
- Step 2: The subjects can emit values. We can use the
nextmethod to emit the value to its subscribers. Call the
complete & errormethod to raise complete & error notifications.
- Step 3: We subscribe to it just like any other observable and get the value in any component.
Subjects are accessible for all unrelated components too.
The subject is an Observable
The subject is observable. It must have the ability to emit a stream of value. The previous example shows, that we can use the
next method to emit values into the stream.
What are the BehaviorSubjects?
BehaviorSubject requires an initial value and stores the current value and emits it to the new subscribers. So In
BehaviorSubject we can give an initial value.
Let’s create a new
BehaviorSubject providing it an initial value or seed value. The
BehaviorSubject stores the initial value.
- Step 1:
- Step 2:
- Step 3:
As soon as the first subscriber subscribes to it, the BehaviorSubject emits the stored value. i.e.
0 and we emit two more values. The
BehaviorSubject stores the last value emitted i.e. 3.
So, in this blog, we have gone through the introduction of Rxjs
BehaviorSubject. Next, we went through how we can create a Subject and BehaviorSubject in angular. To learn more about
Rxjs you can go through the official documentation here.
For more updates, please follow our LinkedIn page- FrontEnd Studio.
Thank you for sticking to the end. If you like the blog, please don’t forget to give a thumbs up and share it. Feel free to share your thoughts about this blog in the comments.