Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS: How to not subscribe to initial value and/or undefined?

Being new to RxJS I often create a subject which holds values in the future, but is initially undefined. It can only be undefined the first time. I currently use a filter to skip undefined values, but this is quite cumbersome as I do it everywhere as I need only once. (Maybe I do something wrong here?) Can I somehow subscribe to mySubject only after it got its first value via onNext?

var mySubject = new Rx.BehaviorSubject(undefined);  mySubject.filter(function(value) {   return value !== undefined; }).subscribe(function(value) {   // do something with the value }); 
like image 949
Pipo Avatar asked Feb 04 '15 06:02

Pipo


People also ask

How do I subscribe to Observable only once?

If you want to call an Observable only one time, it means you are not going to wait for a stream from it. So using toPromise() instead of subscribe() would be enough in your case as toPromise() doesn't need unsubscription.

What is ReplaySubject RxJS?

ReplaySubject is a variant of a Subject which keeps a cache of previous values emitted by a source observable and sends them to all new observers immediately on subscription. This behavior of replaying a sequence of old values to new subscribes is where the name for this type of a subject comes from.

How do I get my ReplaySubject value?

subscribe(num => console. log('last: ' + num)); If you don't want your stream to end, but you do want subscribers to receive the last value emitted before subscription, consider reaching for BehaviorSubject , which was designed for this use case.

What is RxJS BehaviorSubject?

BehaviorSubject is a variant of a Subject which has a notion of the current value that it stores and emits to all new subscriptions. This current value is either the item most recently emitted by the source observable or a seed/default value if none has yet been emitted.


1 Answers

Use new Rx.ReplaySubject(1) instead of BehaviorSubject.

like image 126
Brandon Avatar answered Sep 21 '22 00:09

Brandon