What is Subject variable in AngularJS? How it is different from Observable/RxJs?
Loading
What is Subject variable in AngularJS? How it is different from Observable/RxJs?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Aman GuptaPosted Jul 28, 2021, 6:07 AM
BehaviorSubject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are:
next()onnextgetValue()method.Unique features of a subject compared to an observable are:
In addition, you can get an observable from behavior subject using the
asObservable()method onBehaviorSubject.Observable is a Generic, and
BehaviorSubjectis technically a sub-type of Observable because BehaviorSubject is observable with specific qualities.Example with BehaviorSubject:
Example 2 with the regular subject:
An observable can be created from both
SubjectandBehaviorSubjectusingsubject.asObservable().The only difference being you can't send values to an observable using
next()method.In Angular services, I would use
BehaviorSubjectfor a data service as an angular service often initializes before component and behavior subject ensures that the component consuming the service receives the last updated data even if there are no new updates since the component's subscription to this data.