![](/img/trans.png)
[英]Angular 4+ ngOnDestroy() in service - destroy observable
[英]Angular Observable destroy with takeUntil: What happens when .next() is missing in ngOnDestroy
在 Angular 7 组件中,我使用 RxJS takeUntil() 正确取消订阅可观察订阅。
ngOnDestroy
方法中缺少this.destroy$.next()
时会发生什么(参见下面的示例)? 它仍然会正确退订吗?ngOnDestroy
方法中缺少this.destroy$.complete()
时会发生什么(参见下面的示例)? 它仍然会正确退订吗?
@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
将 next 作为发射。 如果只调用了complete()
则不会取消订阅试试这个:
const a=new Subject();
interval(1000).pipe(takeUntil(a)).subscribe(console.log);
timer(3000).subscribe(_=>a.complete())
this.destroy$
仍在 memory 中,不会被垃圾回收还请查看此处以避免在使用takeUntil
时发生 memory 泄漏。
https://medium.com/angular-in-depth/rxjs-avoiding-takeuntil-leaks-fb5182d047ef
我个人更喜欢在销毁时明确unsubscribe
。
this.destroy$.next()
触发 Subject 触发takeUntil
操作符,完成flightService.getAll()
订阅。
this.destroy$.complete()
在组件被销毁时完成destroy$
Subject。
嗨使用takeWhile而不是takeUntil 。
@Component({
selector: 'app-flights',
templateUrl: './flights.component.html'
})
export class FlightsComponent implements OnDestroy, OnInit {
private readonly destroy$ = new Subject();
alive = true;
public flights: FlightModel[];
constructor(private readonly flightService: FlightService) { }
ngOnInit() {
this.flightService.getAll()
.pipe(takeWhile(() => this.alive))
.subscribe(flights => this.flights = flights);
}
ngOnDestroy() {
this.alive = false;
this.destroy$.complete();
}
}
这是一个更简单的方法:
private readonly destroy$ = new Subject<boolean>();
...
ngOnDestroy() {
this.destroy$.next(true);
this.destroy$.unsubscribe();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.