Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the "current" value of an Observer at subscribe-time

I'm having a hard time grokking one particular part of RxJs: when you subscribe to an Observable, you're only subscribing to any future events from that Stream. Compare to Promises, where, if the promise has been resolved, you will get that value no matter when you call then().

Here's a code example:

var subject = new Rx.Subject();    subject.onNext('old value');  subject.onNext('before subscription');    subject.subscribe(function(val) {    document.write(val);  });    subject.onNext('after subscription');
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.3.24/rx.all.js"></script>

I would expect to see both "before subscription" and "after subscription" printed, although it makes sense to me that "old value" would get dropped. But it seems that RxJs doesn't work that way (only "after subscription" is printed). How can I get the result I'm after?

like image 965
DallonF Avatar asked Feb 03 '15 23:02

DallonF


1 Answers

Rx offers both behaviors (as well as others).

The different Rx Subjects available can let you explore the different ways observables can behave:

  • the Rx.Subject is the most basic fire-and-forget variety -- if you were not subscribed when the event happened, then you do not see it.

  • Use new Rx.BehaviorSubject(undefined) instead of Subject and you get the behavior you were looking for, since a BehaviorSubject represents a "value that can change"

  • Use new Rx.ReplaySubject(5) and you'll get the 5 most recent values as soon as you subscribe

  • Use new Rx.AsyncSubject() and you will get nothing until the observable completes at which time you will get the final value (and continue to get the final value if you subscribe again). This is the true Rx analog of Promises, since it produces nothing until it "resolves" (i.e. completes), and afterwards always gives the value to anyone that subscribes.

like image 166
Brandon Avatar answered Sep 22 '22 20:09

Brandon