rxjs merge.complete() 会关闭对其所有输入流的订阅吗?

Raf*_*Grz 5 rxjs angular

在下面的情况下, .pipe(takeUntil(this.unsubscribe)) 会关闭对所有输入流的订阅吗?

protected unsubscribe: Subject<void>;

public ngOnDestroy(): void {
   this.unsubscribe.next();
   this.unsubscribe.complete();
}

merge(
  this.productsSelect.selected,
  this.productsSelect.removed,
  this.productsSelect.typed)
  .pipe(takeUntil(this.unsubscribe))
  .subscribe(() => {
    this.detectChanges();
  );
Run Code Online (Sandbox Code Playgroud)

Kur*_*ton 4

takeUntil当传递给订阅的可观察对象收到通知时,将关闭订阅。

举个例子:

private destroyed$ = new Subject();
private sub: Subscription;

ngOnInit() {
  this.sub = merge(
    this.obs1(),
    this.obs2()
  ).pipe(
    takeUntil(this.destroyed$)
  ).subscribe(result => {
    console.log(result);
  }, () => {}, () => {
      console.log('complete');
  });
}

ngOnDestroy() {
  // this.sub is still open
  console.log(this.sub);

  // now close the subscription indirectly
  this.destroyed$.next();
  this.destroyed$.complete();

  // this.sub is now closed
  console.log(this.sub);
}

private obs1(): Observable<any> {
  return timer(0, 1000).pipe(mapTo('Hello, '));
}

private obs2(): Observable<any> {
  return timer(0, 1500).pipe(mapTo('World!'));
}
Run Code Online (Sandbox Code Playgroud)

当组件位于 DOM 中时,两个可观察量将继续触发,并且合并订阅将从可观察量接收值timer

当组件从 DOM 中移除时,ngOnDestroy将会触发。第一个console.log(this.sub)将显示订阅已开放。第二个将显示它已关闭。

从控制台:

对象 { 关闭: false,... }

对象 { 关闭: true, ... }

演示: https: //stackblitz.com/edit/angular-8c9nkd