BehaviorSubject

So far, we have been looking at the default type of Subject, and we have uncovered a little of its secrets. However, there are many more types of Subjects. One such interesting type of Subject is the BehaviorSubject. So, why do we need a BehaviorSubject, and for what? Well, when dealing with a default Subject, we are able to add values to the stream, as well as subscribe to the stream. The BehaviorSubject gives us some added capabilities, in the form of:

  • A starter value, which is great if we are able to show something to the UI while waiting for an AJAX call to finish
  • We can query on the latest value; in some situations, it is interesting to know what the last emitted value was

To address the first bullet, let's write some code and showcase this capability:

// subjects/behavior-subject.js

let behaviorSubject = new Rx.BehaviorSubject("default value");

// will emit 'default value'
behaviorSubject.subscribe(data => console.log(data));

// long running AJAX scenario
setTimeout(() => {
return Rx.Observable.ajax("data.json")
.map(r => r.response)
.subscribe(data => behaviorSubject.next(data));
}, 12000);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.9.12