Subject and behavior subject

by guangjungg

HTML

<script src="https://unpkg.com/rxjs@5.2.0/bundles/Rx.min.js"></script>

JavaScript

// Regular Subject

let subject = new Rx.Subject(); 

subject.next("b");
subject.next("c");

subject.subscribe((value) => {
  console.log("Subject Subscription got", value); // Subscription wont get 
                                          // anything at this point
});

subject.next("c"); // Subscription got c
subject.next("d"); // Subscription got d


// Behavior Subject

// a is a initial value. if there is a subscription 
// after this, it would get "a" value immediately
let bSubject = new Rx.BehaviorSubject("a"); 

bSubject.next("b");

bSubject.subscribe((value) => {
  console.log("BehaviorSubject 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 d