HiveBrain v1.2.0
Get Started
← Back to all entries
gotchatypescriptangularCritical

What is the difference between Subject and BehaviorSubject?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
andbetweenthedifferencebehaviorsubjectwhatsubject

Problem

I'm not clear on the difference between a Subject and a BehaviorSubject. Is it just that a BehaviorSubject has the getValue() function?

Solution

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

Subject example (with RxJS 5 API):

const subject = new Rx.Subject();
subject.next(1);
subject.subscribe(x => console.log(x));


Console output will be empty

BehaviorSubject example:

const subject = new Rx.BehaviorSubject(0);
subject.next(1);
subject.subscribe(x => console.log(x));


Console output: 1

In addition:

  • BehaviorSubject should be created with an initial value: new Rx.BehaviorSubject(1)



  • Consider ReplaySubject if you want the subject to get previously published values.

Code Snippets

const subject = new Rx.Subject();
subject.next(1);
subject.subscribe(x => console.log(x));
const subject = new Rx.BehaviorSubject(0);
subject.next(1);
subject.subscribe(x => console.log(x));

Context

Stack Overflow Q#43348463, score: 594

Revisions (0)

No revisions yet.