Angular Observable 使用 takeUntil 销毁:ngOnDestroy 中缺少 .next() 时会发生什么

Hor*_*ley 5 unsubscribe observable rxjs angular

在 Angular 7 组件中,我使用 RxJS takeUntil() 正确取消订阅可观察订阅。

  • this.destroy$.next()方法中缺少时会发生什么ngOnDestroy(参见下面的示例)?它仍然会正常退订吗?
  • this.destroy$.complete()方法中缺少时会发生什么ngOnDestroy(参见下面的示例)?它仍然会正常退订吗?
  • 有什么方法可以强制使用 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Fan*_*ung 3

  1. 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)
  1. this.destroy$仍然在内存中并且不会被垃圾收集
  2. 我不知道

另请查看此处,以避免使用时出现内存泄漏takeUntil

https://medium.com/angular-in-depth/rxjs-avoiding-takeuntil-leaks-fb5182d047ef

我个人更喜欢unsubscribe在销毁时明确。