How to unsubscribe/stop Observable?

混江龙づ霸主 提交于 2019-12-09 11:18:56

问题


I use the following code for timer:

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();
    }
  }
}

When I try to stop timer in line:

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

It does not work for me


回答1:


The subscribe method returns a Subscription object, which you can later use to stop listening the stream contained by the observable to which you subscribed.

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();
    }
  }
}

Its important to notice that unsubscribe exist in rxjs (version 5 and up), before that, in rx (version lower than 5, a different package) the method was called dispose




回答2:


The best way is to unsubscribe when instance is destroyed.

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



回答3:


So after some PUNISHING research I've added my own npm library for this problem.

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

  • StackBlitz
  • Repo
  • NPM



来源:https://stackoverflow.com/questions/45233534/how-to-unsubscribe-stop-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!