How to get the "current" observer value during subscription

It's hard for me to smash one part of RxJs: when you subscribe to Observable, you only subscribe to any future events from this stream. Compare with Promises, where if the promise is resolved, you will get this value no matter when you call then() .

Here is a sample code:

 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", although it makes sense to me that the "old value" will be reset. But it seems that RxJs does not work like this (it is printed only "after subscription"). How can I get the result that I need?

+43
javascript rxjs
Feb 03 '15 at 23:59
source share
1 answer

Rx offers both behaviors (like others).

different Rx objects can allow you to explore different ways in which you can observe observables:

  • Rx.Subject is the easiest option with fire and oblivion - if you were not signed when the event occurred, you will not see it.

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

  • Use new Rx.ReplaySubject(5) and you will get the 5 most recent values ​​right after signing

  • Use new Rx.AsyncSubject() , and you will not get anything until the observable is complete, and at that time you will get the final value (and continue to get the final value if you subscribed again). This is the true Rx analogue of Promises, since it does not produce anything until it "resolves" (that is, it does not complete), and then always gives meaning to anyone who signs up.

+78
Feb 04 '15 at 3:39
source share



All Articles