我什么时候应该使用 `publishReplay` 和 `shareReplay`? [英] When should I use `publishReplay` vs `shareReplay`?

查看:43
本文介绍了我什么时候应该使用 `publishReplay` 和 `shareReplay`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道了

  • publish 共享一个订阅并返回一个 ConnectableObservable(所以我们必须Connect())

  • publish shares a single subscription and also returns a ConnectableObservable ( so we have to Connect())

Share()publish().refcount()

Replay 后缀非常明显,它返回最后一次发射.

The Replay postfix is pretty obvious, it returns its last emission/s.

让我们以现在和未来订阅的 Angular HTTP 请求为例:

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 -->

如果我不想要多个 http 请求,我可以使用:

If I don't want multiple http requests I can use :

publishReplay().Connect()

但我也可以使用:shareReplay(),但我确信这里有一个比另一个更正确使用.

But I can also use: shareReplay(), but I'm sure that there is one here that is more correct to use than the other.

问题:

我应该什么时候使用 publishReplayshareReplay?就 HTTP 存在而言,这将有何不同?未来的要求?

When should I use publishReplay vs shareReplay? What will be the difference in terms of that HTTP present & future request?

注意为什么没有关于 shareReplay 的文档?

NB Why there's no documentation about shareReplay?

推荐答案

publishReplay 允许您控制订阅何时开始.shareReplay 将在第一次订阅时自动启动.

publishReplay allows you to controls when the subscription starts. shareReplay will start automatically upon the first subscription.

通常,如果要在模板(html 文件)中使用可观察对象,请使用 shareReplay.优点是您不必担心取消订阅等.

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.

这篇关于我什么时候应该使用 `publishReplay` 和 `shareReplay`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆