繁体   English   中英

Angular 使用 takeUntil 进行可观察销毁:ngOnDestroy 中缺少.next() 时会发生什么

[英]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()时会发生什么(参见下面的示例)? 它仍然会正确退订吗?
  • 有什么方法可以强制使用 takeUntil() 取消订阅的模式被正确使用(例如 tslint 规则,npm 包)?

@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();
    }
}
  1. takeUntil将 next 作为发射。 如果只调用了complete()则不会取消订阅

试试这个:

const a=new Subject();
interval(1000).pipe(takeUntil(a)).subscribe(console.log);
timer(3000).subscribe(_=>a.complete())
  1. this.destroy$仍在 memory 中,不会被垃圾回收
  2. 不是我知道

还请查看此处以避免在使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM