如何取消订阅/停止Observable?

时间:2017-07-21 09:04:50

标签: angular rxjs observable

我将以下代码用于计时器:

export class TimerService {
  private ticks: number = 0;
  private seconds: number = 0;
  private timer;

  constructor(seconds: number) {
    this.seconds = seconds;
    this.timer = Observable.timer(2000, 1000);
    this.timer.subscribe(t => {
      this.ticks = t;
      this.disactivate();
    });
  }

  private disactivate() {
    if (this.ticks === this.seconds) {
      this.timer.dispose();
    }
  }
}

当我尝试在线停止计时器时:

this.timer.dispose(); // this.timer.unsubscribe();

它对我不起作用

4 个答案:

答案 0 :(得分:12)

subscribe方法返回一个Subscription对象,稍后您可以使用该对象停止侦听您订阅的observable所包含的流。

import { ISubscription } from 'rxjs/Subscription':
import { TimerObservable } from 'rxjs/observable/TimerObservable';

export class TimerService {
  private ticks = 0;
  private timer$: TimerObservable;
  private $timer : ISubscription;

  constructor(private seconds = 0) {
    this.timer$ = TimerObservable.create(2000, 1000);//or you can use the constructor method
    this.$timer = this.timer.subscribe(t => {
      this.ticks = t;
      this.disactivate();
    });
  }

  private disactivate() {
    if (this.ticks >= this.seconds) {
      this.$timer.unsubscribe();
    }
  }
}

重要的是要注意到unsubscribe存在于rxjs(版本5及更高版本)中,在此之前,在rx(版本低于5,不同的包)中,该方法被称为dispose

答案 1 :(得分:0)

最好的方法是在实例销毁时退订。

ngOnDestroy() {
 this.sub.unsubscribe();
}

答案 2 :(得分:0)

因此,在进行了一些惩罚研究之后,我为这个问题添加了自己的npm库。

Improves previous answer by NOT having to add any extra convolution variables and ease of use.

enter image description here

答案 3 :(得分:0)

我还没有使用过计时器,但我认为这个概念仍然有效。我使用的方法是使用服务。

(作品基于:https://medium.com/angular-in-depth/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0

  1. 创建我的 new BehaviorSubject<T>(T)
  2. 创建一个 new Subscription() 对象。
  3. 使用 addSubscription 方法包装订阅。
  4. 当父组件或更高层组件被销毁时ngOnDestroy(): void取消订阅

服务

private organisation = new BehaviorSubject<__Organisation>(newOrganisation);
organisation$ = this.organisation.asObservable();

private organisationSubscription: Subscription = new Subscription();

服务方式

addOrganisationSubscription(subscription: Subscription): void {
    this.organisationSubscription.add(subscription);
}
unSubscribeOrganisation(): void {
    this.organisationSubscription.unsubscribe();
}

addOrganisationSubscription(subscription: Subscription): void {
   this.organisationSubscription.add(subscription);
}

组件

this.organisationService.addOrganisationSubscription(
      this.organisationService.organisation$.subscribe(
      ...
      )
)

ngOnDestroy(): void {
    this.organisationService.unSubscribeOrganisation();
}