So a quick question. I've been using RxJS 5 for a few months now, and I've run into a bit of behavior that I don't really understand, as I haven't been able to look it up anywhere.
I'm in a situation where subscribing to an observable chain with simply .subscribe();
doesn't trigger the observable.
However, if I add an onNext callback (empty or not), the observable triggers, and the chain processes: .subscribe(() => {});
Can anyone explain why this behavior happens?
If you don't subscribe nothing is going to happen. It's good to know that when you subscribe to an observer, each call of subscribe() will trigger it's own independent execution for that given observer. Subscribe calls are not shared among multiple subscribers to the same observable.
Executing an Observable But the observable function does not emit any values until it is executed. The subscribe() method calls the observable's function that produces and emits data. Thus, subscribing to an observable starts a flow of data between the observable and the observer.
It turns out that as the Observable is just a definition, let's remember that in a sense its something close to a function declaration, if we subscribe to it multiple times this means that each time a new HTTP request will be issued, one for each subscription.
It triggers the call and handles the result. Coming back to the main topic of the article, if you are writing a lot of logic inside the subscribe callback, you are using an Observable as if it was a Promise. Thus, you are not making an optimal use of RxJS or Angular features.
.subscribe()
actually doesn't require any parameters, it will just create an emptyObserver
if none are given, which should work just as well.
It is possible though, that there are issues related to this in some of the 5.0.0-beta versions - in case you are using one of those versions, you should update to a more stable release.
const obs$ = Rx.Observable.of("Foo")
.do(() => console.log("triggered!"));
obs$.subscribe();
obs$.subscribe();
<script src="https://unpkg.com/[email protected]/bundles/Rx.min.js"></script>
Thanks to Damian Hercun for informing that this was a now-fixed bug in RxJS 5.4.2.
Info:
https://github.com/ReactiveX/rxjs/pull/1935
https://github.com/ReactiveX/rxjs/issues/1921
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