Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - How to unsubscribe/stop Observable?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...