如果Observable使用异步管道,是否需要取消订阅? [英] Is unsubscribe needed if an Observable uses an async pipe?

查看:58
本文介绍了如果Observable使用异步管道,是否需要取消订阅?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定两种不同的处理Observable的方法是否同样有效,或者是否会导致内存问题.

I need to determine whether two different approaches for handling Observables are equally valid, or if one will cause memory issues.

在下面的示例中, foo $ bar 是从服务接收其值的模板变量.每个都有自己的Observable.在该组件中, bar 从订阅中被明确赋予其值,然后在 OnDestroy()中结束该订阅.但是, foo $ 不会显式订阅服务,而是在模板中使用 async 管道.

In the following example, foo$ and bar are template variables that receive their values from a service. Each has its own Observable. In the component, bar is explicitly given its value from a subscription and later ends that subscription in OnDestroy(). foo$, however, does not explicitly subscribe to a service but rather uses an async pipe in the template.

foo $ bar 都是显示服务数据的有效方法,还是 foo $ 有问题,因为没有取消预订内存清理?

Are foo$ and bar both valid ways of displaying the service data, or is foo$ problematic because there is no unsubscribing for memory cleanup?

ExampleService:

Injectable()
export class ExampleService {
    get foo$(): Observable<string> {
        return data.from.api;
    }

    get bar$: Observable<string> {
        return data.from.api;
    }
}

示例组件:

@Component({
    template: `
        <div>{{ foo$ | async }}</div>
        <div>{{ bar }}</div>
    `
})
export class ExampleComponent implements OnInit, OnDestroy {
    public foo$ = this._exampleService.foo$;
    public bar = '';
    private _destroy$ = new Subject();

    constructor(private _exampleService: ExampleService) {}

    public ngOnInit() {
        this._exampleService.bar$
            .pipe(takeUntil(this._destroy$))
            .subscribe(bar => this.bar = bar);
    }

    /**
     * Cancel subscriptions.
     */
    public ngOnDestroy() {
        this._destroy$.next(true);
        this._destroy$.complete();
    }
}

推荐答案

来自角度团队

异步管道订阅Observable或Promise并返回它发出的最新值.发出新值时,异步管道标记要检查的组件是否有更改.当组件被销毁后,异步管道会自动取消订阅以避免潜在的内存泄漏.

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

因此,异步管道负责订阅和解包数据,以及在组件被破坏时取消订阅.

So the async pipe takes care of subscribing and unwrapping the data as well as unsubscribing when the component is destroyed.

这篇关于如果Observable使用异步管道,是否需要取消订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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