问题描述
在组件模板中,我在2个地方为相同的Observable调用async
管道.
In my component template I am calling async
pipe for same Observable in 2 places.
我应该订阅它并在模板中使用返回的数组,还是对模板的多个位置中的同一Observable使用async
管道,对性能没有负面影响?
Shall I subscribe to it and use returned array in my template or using async
pipe for same Observable in multiple places of template has no negative effect to performence?
推荐答案
每次使用observable$ | async
都会为给定的observable$
创建新的订阅(并因此生成单独的流)-如果此可观察项包含计算繁重的部分或重新调用,这些计算和重新调用是针对每个async
单独执行的-所以-此可以会对性能产生影响.
Every use of observable$ | async
will create a new subscription(and therefor an individual stream) to the given observable$
- if this observable contains parts with heavy calculations or rest-calls, those calculations and rest-calls are executed individually for each async
- so yes - this can have performance implications.
但是,通过使用,以便在所有订阅者之间共享流,并为所有订阅者一次执行所有这些操作.不要忘记将share
-运算符与import "rxjs/add/operator/share";
However this is easily fixed by extending your observable$
with .share()
, to have a shared stream among all subscribers and execute all those things just once for all subscribers.Don't forget to add the share
-operator with import "rxjs/add/operator/share";
默认情况下,异步管道不共享订阅的原因仅仅是灵活性和易用性:简单的.share()
的编写速度比创建全新的流要快得多,如果要创建新的流,则必须这样做默认为共享.
The reason why async-pipes don't share subscriptions by default is simply flexibility and ease of use: A simple .share()
is much faster to write than creating a completely new stream, which would be required if they were to be shared by default.
这是一个简单的例子
@Component({
selector: "some-comp",
template: `
Sub1: {{squareData$ | async}}<br>
Sub2: {{squareData$ | async}}<br>
Sub3: {{squareData$ | async}}
`
})
export class SomeComponent {
squareData$: Observable<string> = Observable.range(0, 10)
.map(x => x * x)
.do(x => console.log(`CalculationResult: ${x}`)
.toArray()
.map(squares => squares.join(", "))
.share(); // remove this line and the console will log every result 3 times instead of 1
}
这篇关于在带有异步管道的模板中的多个位置使用相同的可观察值的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!