本文介绍了取消订阅ReplaySubject的异步管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中提供以下服务来适应全球微调器:

  import {可注射}来自"@ angular/core";进口 {可观察的}来自"rxjs/Observable";进口 {重播主题}来自"rxjs/ReplaySubject";@Injectable()导出类SpinnerService {私人可见=新的ReplaySubject<布尔>();showSpinner(){this.visible.next(true);}hideSpinner(){this.visible.next(false);}getSpinnerVisibility():可观察<布尔>{返回this.visible.asObservable();}}  

然后在我的主应用程序组件中,在我的 router-outlet 上方的以下位置:

< app-spinner * ngIf ="spinnerService.getSpinnerVisibility()|异步"></app-spinner>

问题是,此处的 async 管道是否应正常运行才能取消订阅,而不会因该 ReplaySubject 引起内存泄漏?还是我必须手动取消订阅?

从订阅者的角度来看, ReplaySubject Observable 之间绝对没有区别.使用 async 管道时,您不必取消订阅可观察对象,因此对于 ReplaySubject ,它是相同的.

I have the following service to accommodate for a global spinner in my app:

import {
  Injectable
} from '@angular/core';
import {
  Observable
} from 'rxjs/Observable';
import {
  ReplaySubject
} from 'rxjs/ReplaySubject';

@Injectable()
export class SpinnerService {
  private visible = new ReplaySubject < boolean > ();

  showSpinner() {
    this.visible.next(true);
  }

  hideSpinner() {
    this.visible.next(false);
  }

  getSpinnerVisibility(): Observable < boolean > {
    return this.visible.asObservable();
  }
}

Then the following just above my router-outlet in my main app component:

<app-spinner *ngIf="spinnerService.getSpinnerVisibility() | async "></app-spinner>

The question is, should the async pipe here function as normal to unsubscribe without memory leaks from this ReplaySubject or do I have to manually unsubscribe?

解决方案

There is absolutely no difference between a ReplaySubject and an Observable from the subscriber's point of view. You don't have to unsubscribe from an observable when you use the async pipe, so it's the same for a ReplaySubject.

这篇关于取消订阅ReplaySubject的异步管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 21:20