Prev Next

Web / Typescript interview questions

What is the difference between Subject and BehaviorSubject?

A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A Subject doesn't hold value.

BehaviourSubject will return the initial value or the current value on Subscription.

var bSubject= new Rx.BehaviorSubject(0);  // 0 is the initial value

bSubject.subscribe({
  next: (v) => console.log('observerA: ' + v)  // output initial value, then new values on `next` triggers
});

bSubject.next(1);  // output new value 1 for 'observer A'
bSubject.next(2);  // output new value 2 for 'observer A', current value 2 for 'Observer B' on subscription

bSubject.subscribe({
  next: (v) => console.log('observerB: ' + v)  // output current value 2, then new values on `next` triggers
});

bSubject.next(3);

Subject does not return the current value on Subscription. It triggers only on .next(value) call and return/output the value.

var subject = new Rx.Subject();

subject.next(1); //Subjects will not output this value

subject.subscribe({
  next: (v) => console.log('observerA: ' + v)
});
subject.subscribe({
  next: (v) => console.log('observerB: ' + v)
});

subject.next(2);
subject.next(3);

More Related questions...

Show more question and Answers...


Comments & Discussions