可观察到的混乱

时间:2018-02-20 10:43:41

标签: angular observable

我遇到了关于如何使用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

1 个答案:

答案 0 :(得分:3)

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

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

this.gps.takeUntil(this.ngUnsubscribe);

创建新的可观察对象,但this.gps不会改变 您需要组合创建observable并添加.takeUntil运算符

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