I'm looking into the design patterns of RxJS, and I do not understand the difference between BehaviorSubject
and Observable
.
From my understanding, BehaviorSubject can contain a value that may change. It can be subscribed to and subscribers can receive updated values. Both seem to have the exact same purpose.
BehaviorSubject
is a variant of Subject
, a type of Observable
to which one can "subscribe" like any other Observable.
next()
onNext()
getValue()
asObservable()
// BehaviorSubject.
// 'A' is an initial value. If there is a Subscription
// after it, it would immediately get the value 'A'.
beSubject = new BehaviorSubject('a');
beSubject.next('b');
beSubject.subscribe(value => {
console.log('Subscription received the value ', value);
// Subscription received B. It would not happen
// for an Observable or Subject by default.
});
beSubject.next('c');
// Subscription received C.
beSubject.next('d');
// Subscription received D.
// Subject.
subject = new Subject();
subject.next('b');
subject.subscribe(value => {
console.log('Subscription received the value ', value);
// Subscription won't receive anything at this point.
});
subject.next('c');
// Subscription received C.
subject.next('d');
// Subscription received D.
An Observable can be created from both Subject
and BehaviorSubject
; for example, subjectName.asObservable()
.
The only difference is that one cannot send values to an Observable using the method next()
.
In Angular, it is recommended to use BehaviorSubject
for transferring data as a Service is often initialised before a component.
BehaviorSubject ensures that the component consuming the Service receives the last updated data, even if there are no new updates, due to the subscription of the component to the Service.