使用异步管道在模板中的多个位置使用相同的 observable 的性能 [英] Performance of using same observable in multiple places in template with async pipe

查看:19
本文介绍了使用异步管道在模板中的多个位置使用相同的 observable 的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的组件模板中,我在两个地方为同一个 Observable 调用 async 管道.

In my component template I am calling async pipe for same Observable in 2 places.

我应该订阅它并在我的模板中使用返回的数组,还是在模板的多个位置使用 async 管道对同一个 Observable 没有负面影响?

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$ 创建一个新订阅(并为此创建一个单独的流) - 如果这个 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(),在所有订阅者之间共享一个流,并为所有订阅者只执行一次所有这些事情.不要忘记添加 share-operator 和 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
}

这篇关于使用异步管道在模板中的多个位置使用相同的 observable 的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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