我需要完成一个只用于组成另一个可观察对象的主题吗?



嗨,我有以下组件:


export class PreviewReportComponent implements OnInit, OnChanges, OnDestroy {
@Input() params: PreviewParams;
reload$: Subject<void> = new Subject();
preview$: Observable<SafeHtml>;
constructor(private reportService: ReportService) {}
ngOnInit() {
this.preview$ = this.reload$.pipe(
debounceTime(200),
startWith([null]),
switchMap(() => this.reportService.getPreview(this.params)),
);
}
ngOnChanges() {
this.reload$.next();
}
ngOnDestroy(){
this.reload$.complete();
}
}

我需要实现OnDestroy和调用reload$ subject完成吗?

我已经使用AsyncPipe来订阅预览$ Observable。

我是否需要实现OnDestroy并在reload$ subject上调用complete ?

如果你担心的是内存泄漏,那么NO,没有必要实现OnDestroy来完成你的主题,因为你没有订阅你的组件。当组件销毁后订阅保持打开状态时,就会发生内存泄漏。

由于您使用AsyncPipe来处理订阅,因此您不需要担心它。


实际上,你甚至不需要OnInit:

export class PreviewReportComponent implements OnChanges {
@Input() params: PreviewParams;
private reload$ = new Subject<void>();
public preview$ = this.reload$.pipe(
startWith([null]),
debounceTime(200),
switchMap(() => this.reportService.getPreview(this.params)),
);
constructor(private reportService: ReportService) {}
ngOnChanges() {
this.reload$.next();
}
}

您也可以摆脱OnChanges,如果您将参数更改为setter:

export class PreviewReportComponent {
private params$ = new Subject<PreviewParams>();
@Input() set params(params: PreviewParams) {
this.params$.next(params);
}
public preview$ = this.params$.pipe(
startWith([null]),
debounceTime(200),
switchMap(params => this.reportService.getPreview(params)),
);
constructor(private reportService: ReportService) {}
}

最新更新