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 });
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.
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.
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.
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.
Use new Rx.ReplaySubject(1)
instead of BehaviorSubject
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With