【问题标题】:Observable takeUntil confusionObservable takeUntil 混淆
【发布时间】:2018-07-30 16:55:22
【问题描述】:

我遇到了这个关于如何使用 takeUntil() 停止订阅的答案 Angular/RxJs When should I unsubscribe from `Subscription`。答案还指出

秘诀(正如@metamaker 已经指出的)是在我们每个 .subscribe() 调用之前调用 .takeUntil(this.ngUnsubscribe) ,这将保证在组件被销毁时所有订阅都将被清除。

但是,我无法理解为什么我的两个示例之一不会停止订阅。 Here is a working example

我的服务:

export class GpsService {
  gps: Observable<any>;
  private ngUnsubscribe: Subject<any> = new Subject<any>();
  constructor() { }
  startFakeGps = (): void => {
    // This example does not stop the subscription after calling stopGps().
    this.gps = Observable.timer(3000, 1000);
    this.gps.takeUntil(this.ngUnsubscribe);

    // This example stops the subscription after calling stopGps().
    // this.gps = Observable.timer(3000, 1000).takeUntil(this.ngUnsubscribe);
  }

  stopGps() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}

我的组件:

export class ButtonOverviewExample implements OnInit {

  constructor(private gspService: GpsService){

  }
  ngOnInit(){
    this.gspService.startFakeGps();
    this.gspService.gps.subscribe(data => {});
  }

  // stop gps after clicking a button 
  stopGps(){
    this.gspService.stopGps();
  }


}

示例 1:

    // This example does not stop the subscription after calling stopGps().
    this.gps = Observable.timer(3000, 1000);
    this.gps.takeUntil(this.ngUnsubscribe);

示例 2:

    // This example stops the subscription after calling stopGps().
    this.gps = Observable.timer(3000, 1000).takeUntil(this.ngUnsubscribe);

我认为这两个示例在实际订阅开始之前都使用了takeUntil(),并且它们是相同的。为什么这些示例的行为不同?我错过了什么?

Here is a working example

【问题讨论】:

    标签: angular observable


    【解决方案1】:
    this.gps = Observable.timer(3000, 1000);
    

    创建 observable 并将其保存在 this.gps

    this.gps.takeUntil(this.ngUnsubscribe);
    

    创建新的 observable,但 this.gps 没有改变 您需要结合创建 observable 和添加 .takeUntil 运算符

    this.gps = Observable.timer(3000, 1000).takeUntil(this.ngUnsubscribe);
    

    【讨论】:

    • 确切地说,rxjs 操作符不会改变底层的 Observable,它们会创建一个你必须存储的新的。所以或者(但不是很好的风格)这会起作用:this.gps = this.gps.takeUntil(this.ngUnsubscribe);
    • 感谢您的回答。在了解它创建了一个新的 observable 之后,一切都变得有意义了。
    • 小心,有时你必须使用扁平箭头 Observable.takeUntil(() => this.ngUnsubscribe).subscribe()
    猜你喜欢
    • 2017-11-13
    • 2016-07-13
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多