Hor*_*ley 5 unsubscribe observable rxjs angular
在 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();
}
}
Run Code Online (Sandbox Code Playgroud)
takeUntil接下来作为发射。如果只complete()调用它不会取消订阅试试这个:
const a=new Subject();
interval(1000).pipe(takeUntil(a)).subscribe(console.log);
timer(3000).subscribe(_=>a.complete())
Run Code Online (Sandbox Code Playgroud)
this.destroy$仍然在内存中并且不会被垃圾收集另请查看此处,以避免使用时出现内存泄漏takeUntil。
https://medium.com/angular-in-depth/rxjs-avoiding-takeuntil-leaks-fb5182d047ef
我个人更喜欢unsubscribe在销毁时明确。
| 归档时间: |
|
| 查看次数: |
4174 次 |
| 最近记录: |