如何取消订阅/停止 Observable? [英] How to unsubscribe/stop Observable?
本文介绍了如何取消订阅/停止 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();
}
}
}
当我尝试停止排队时:
this.timer.dispose(); // this.timer.unsubscribe();
它对我不起作用
推荐答案
subscribe
方法返回一个 Subscription
对象,您可以稍后使用它来停止侦听包含的流通过您订阅的 observable.
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();
}
}
}
需要注意的是 unsubscribe
存在于 rxjs(版本 5 及以上)中,在此之前,在 rx(版本低于 5,不同的包)中,该方法被称为 dispose代码>
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
这篇关于如何取消订阅/停止 Observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文