Reputation: 24659
I am trying to understand the behavior of the RxJS 5 share()
operator.
According to tutorials and documentation, share()
turns a cold observable into a hot one.
I am trying to see that in action. Here is what I have tried:
const search$ = Rx.Observable.ajax('https://www.googleapis.com/books/v1/volumes?q=javascript').share();
And then the first time I subscribe to it:
search$.subscribe(console.log);
I see from the dev tools that a network request is issued:
Request URL:https://www.googleapis.com/books/v1/volumes?q=javascript
then upon rerunning the same subscription:
search$.subscribe(console.log);
I notice that another network request is also issued.
Can someone please explain why the share()
operator is displaying this behavior? I was expecting just one network request to be issued...
P.S. using xxx.publishLast().refCount();
instead of xxx.share();
does the job but my main concern is to understand the share()
behavior in the above context.
Upvotes: 1
Views: 420
Reputation: 16882
share
is a shortcut for publish().refCount()
. The refCount
-part means, that the stream is hot/shared as long as there is at least 1 subscriber - howver, it is being reset/cold when there are no subscribers. When your ajax
-requests finishes, the stream completes and upon completion of a stream any subscriber is automatically being unsubscribed -> setting the subribers of the stream to 0 and therefor resetting the stream - which is why you are experiencing a second network-quest on any future subscription.
Why does this work with publishLast().refCount()
? - with publishLast()
you get a stream that never completes, therefor no subscriber is automatically unsubscribed and the stream is never being reset.
For caching HTTP-Responses your approach with publishLast().refCount()
is perfectly valid.
Upvotes: 2