Subject in Angular

Rxjs subject is a special type of observable. It acts as a observer as well as observable. 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 & hence the same values. It allows values to be multicasted to many Observers.

Let see how to create the subject.
Add below code app.component.ts file –

In the above code in the App Component firstly we have created the subject. Then we have subscribe to it just like any other observable. The subjects can emit values. You can use the next method to emit the value to its subscribers. Call the complete & error method to raise complete & error notifications.

Subject is an Observable

The subject is observable. It must have the ability to emit a stream of values

In the example you can seenext method is used to emit values into the stream.

Every Subject is an Observer

The observer needs to implement the next, error & Complete callbacks (all optional) to become an Observer.

The following example creates a Subject & and an Observable.We subscribe to the Subject in the ngOnInit method. We also subscribe to the observable, passing the subject. Since the subject implements the next method, it receives the values from the observable and emits them to the subscribers.

Subjects are Multicast

Another important distinction between observable & subject is that subjects are multicast. More than one subscriber can subscribe to a subject. They will share the same instance of the observable. This means that all of them receive the same event when the subject emits it. Multiple observers of an observable, on the other hand, will receive a separate instance of the observable.

Subjects maintain a list of subscribers

Whenever a subscriber subscribes to a subject, it will add it to an array of subscribers. This way Subject keeps track of its subscribers and emits the event to all of them.

Observables are classified into two groups.

  • Cold
  • Hot

There are 3 types of observable.

  • BehaviorSubject
  • ReplaySubject
  • AsyncSubject

We will discuss these group of observableand types of observable in detail in next chapter.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *