在Angular 7组件中,我使用RxJS takeUntil()适当地取消订阅可观察的订阅。
this.destroy$.next()
方法中缺少时会发生什么ngOnDestroy
(请参见下面的示例)?仍然可以正确取消订阅吗?this.destroy$.complete()
方法中缺少时会发生什么ngOnDestroy
(请参见下面的示例)?仍然可以正确取消订阅吗?
@Component({
selector: 'app-flights',
templateUrl: './flights.component.html'
})
export class FlightsComponent implements OnDestroy, OnInit {
private readonly destroy$ = new Subject();
public flights: FlightModel[];
constructor(private readonly flightService: FlightService) { }
ngOnInit() {
this.flightService.getAll()
.pipe(takeUntil(this.destroy$))
.subscribe(flights => this.flights = flights);
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
takeUntil
接下来是排放。如果只complete()
叫它将不会退订试试这个:
const a=new Subject();
interval(1000).pipe(takeUntil(a)).subscribe(console.log);
timer(3000).subscribe(_=>a.complete())
this.destroy$
仍然在内存中,不会收集垃圾也请在这里看看,以避免使用时发生内存泄漏takeUntil
。
https://medium.com/angular-in-depth/rxjs-avoiding-takeuntil-leaks-fb5182d047ef
就我个人而言,我更喜欢unsubscribe
在破坏时明确。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句