Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RXJS 5 .subscribe() without arguments

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?

like image 920
DarkNeuron Avatar asked Feb 19 '17 21:02

DarkNeuron


People also ask

What happens if you don't subscribe to an observable?

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.

Can you subscribe to an 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.

Can you subscribe to observable multiple times?

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.

Why you should not put any logic in the RxJS subscribe callback in Angular?

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.


2 Answers

.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>
like image 193
olsn Avatar answered Sep 19 '22 14:09

olsn


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

like image 42
DarkNeuron Avatar answered Sep 18 '22 14:09

DarkNeuron