I already know that
publish
shares a single subscription and also returns a ConnectableObservable
( so we have to Connect()
)
Share()
is publish().refcount()
The Replay
postfix is pretty obvious, it returns its last emission/s.
Let's take for example an Angular HTTP request with present AND future subscription :
<p>{{ (person | async)?.id }}</p> //present markup
<p *ngIf=”show”>{{ (person | async)?.userId }}</p> <!-- future markup -->
If I don't want multiple http
requests I can use :
publishReplay().Connect()
But I can also use: shareReplay()
, but I'm sure that there is one here that is more correct to use than the other.
Question :
When should I use publishReplay
vs shareReplay
? What will be the difference in terms of that HTTP present & future request?
NB Why there's no documentation about shareReplay
?
shareReplay() is basically publishReplay().refCount()
Definitely not.
Both shareReplay
and publishReplay
(+ calling connect
on it) will make the observable behind it hot.
But the very important difference between them is :
shareReplay
: won't stop emitting until it's completed , no matter if there are no subscriptions anymore or not. publishReplay
: will stop after the last subscriber unsubscribes if used together with refCount
Imho this is a crucial information.
publishReplay
allows you to controls when the subscription starts. shareReplay
will start automatically upon the first subscription.
Generally, if the observable is to be used in a template (html file) use shareReplay
. The advantage being you won't have to worry about unsubscribing etc.
shareReplay()
is basically publishReplay().refCount()
Here is a great article explaingin just that in detail: "Angular Async Pipes - Beware the share"
Edit:
The right thing to say is:
shareReplay()
is similar to publishReplay().refCount()
see @DevRok's answer for more info why they are not exactly the same.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.