blog icon indicating copy to clipboard operation
blog copied to clipboard

Rxjs 使用备忘

Open waltcow opened this issue 7 years ago • 0 comments

Behavior Subject 和 Subject 的区别

Behavior Subject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable

behavior subject 的特性

  • Behavior subject needs an initial value as it must always return a value on subscription even if it hasn’t received a next()
  • Upon subscription, it returns the last value of the subject. A regular observable only triggers when it receives a on next at any point you can retrieve the last value of the subject in a non-observable code using the getValue() method.

举个例子

Behavior Subject

// a is a 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 d

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 d

waltcow avatar Dec 21 '17 02:12 waltcow