[英]When should I use `publishReplay` vs `shareReplay`?
I already know that我已经知道了
publish
shares a single subscription and also returns a ConnectableObservable
( so we have to Connect()
) publish
共享一个订阅并返回一个ConnectableObservable
(所以我们必须Connect()
)
Share()
is publish().refcount()
Share()
是publish().refcount()
The Replay
postfix is pretty obvious, it returns its last emission/s. Replay
后缀非常明显,它返回最后的发射/秒。
Let's take for example an Angular HTTP request with present AND future subscription :让我们以现在和未来订阅的 Angular HTTP 请求为例:
<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 :如果我不想要多个
http
请求,我可以使用:
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.但我也可以使用:
shareReplay()
,但我确信这里有一个比另一个更正确使用。
Question :题 :
When should I use publishReplay
vs shareReplay
?我应该什么时候使用
publishReplay
和shareReplay
? What will be the difference in terms of that HTTP present & future request? HTTP 现在和将来的请求有什么区别?
NB Why there's no documentation about shareReplay
?注意为什么没有关于
shareReplay
的文档?
shareReplay() is basically publishReplay().refCount()
shareReplay() 基本上是 publishReplay().refCount()
Definitely not.当然不。
Both shareReplay
and publishReplay
(+ calling connect
on it) will make the observable behind it hot. shareReplay
和publishReplay
(+ 在其上调用connect
)都会使背后的 observable 变得炙手可热。
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. shareReplay
:在完成之前不会停止发射,无论是否不再有订阅。publishReplay
: will stop after the last subscriber unsubscribes if used together with refCount
publishReplay
: 如果与refCount
一起使用,将在最后一个订阅者取消订阅后停止Imho this is a crucial information.恕我直言,这是一个关键信息。
publishReplay
allows you to controls when the subscription starts. publishReplay
允许您控制订阅何时开始。 shareReplay
will start automatically upon the first subscription. shareReplay
将在第一次订阅时自动启动。
Generally, if the observable is to be used in a template (html file) use shareReplay
.通常,如果要在模板(html 文件)中使用可观察对象,请使用
shareReplay
。 The advantage being you won't have to worry about unsubscribing etc.优点是您不必担心取消订阅等。
shareReplay()
is basically publishReplay().refCount()
shareReplay()
基本上是publishReplay().refCount()
Here is a great article explaingin just that in detail: "Angular Async Pipes - Beware the share"这是一篇很棒的文章,详细解释了这一点: “Angular Async Pipes - Beware the share”
Edit:编辑:
The right thing to say is:正确的说法是:
shareReplay()
is similar to publishReplay().refCount()
shareReplay()
类似于publishReplay().refCount()
see @DevRok's answer for more info why they are not exactly the same.有关为什么它们不完全相同的更多信息,请参阅@DevRok 的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.