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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Aman GuptaRank #193 · 12.4K reputationPosted Jul 28, 2021, 2:07 AM EDT
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:
// Behavior Subject // a is an initial value. if there is a subscription // after this, it would get "a" value immediately let bSubject = new BehaviorSubject("a"); bSubject.next("b"); bSubject.subscribe(value => { console.log("Subscription got", value); // Subscription got b, // ^ This would not happen // for a generic observable // or generic subject by default }); bSubject.next("c"); // Subscription got c bSubject.next("d"); // Subscription got dExample 2 with the regular subject:
// Regular Subject let subject = new Subject(); subject.next("b"); subject.subscribe(value => { console.log("Subscription got", value); // Subscription wont get anything at this point. }); subject.next("c"); // Subscription got c subject.next("d"); // Subscription got dAn 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.