小编Ole*_*r K的帖子

为takeUntil运算符提供了哪种方法更好地杀死可观察对象,为什么?

我对使用Angular和RxJ的takeUntil运算符取消订阅的常见模式之一有疑问。在本文中,它位于第三位置。例如,我们在组件类中有这样的代码:

  private destroy$: Subject<boolean> = new Subject();

  ngOnInit() {
     this.control.
     .pipe(takeUntil(this.destroy$)
     .subscribe(doSmthngFunc); 
  }

  ngOnDestroy() {
    this.destroy$.next(true);
    // Which next line of code is correct?
    // this.destroy$.complete()     // this one?
    // this.destroy$.unsubscribe()  // or this one?
  }
Run Code Online (Sandbox Code Playgroud)

第一行this.destroy $ .next(true)非常清楚。但是第二个不是。如果我们研究这些方法的实现,就会发现它们具有类似的行为。 complete(): unsubscribe():

据我了解,语义上complete()是可取的,因为我们在组件生命周期中第一次和最后一次调用next(),然后我们完成了此Subject,将其视为Observable并可以调用complete()。这些方法属于观察者,而取消订阅则属于可观察者,我们没有要取消订阅的订阅。但实际上,这些方法具有类似的代码:

    this.isStopped = true; // both

    this.observers.length = 0; // complete
    this.observers = null;     // unsubscribe

    this.closed = true;        // only unsubscribe

Run Code Online (Sandbox Code Playgroud)

理论上,complete()可能会延迟作用,因为它可能会在订阅的每个观察者上调用complete(),但是我们在destroy $上没有观察者。因此,问题-哪种方法更可取,更不易出错,为什么?

rxjs angular rxjs-pipeable-operators

5
推荐指数
1
解决办法
131
查看次数

标签 统计

angular ×1

rxjs ×1

rxjs-pipeable-operators ×1