【问题标题】:Can't stop Observable interval无法停止可观察间隔
【发布时间】:2017-10-06 04:33:03
【问题描述】:

我已经尝试了几乎所有我能找到的东西,但似乎无法让这个时间间隔停止在订阅中执行代码。是不是我用错了区间?

var subject = new Subject();
var interval = Observable.interval(this.settings.timing * 1000);
var subscription = interval
  .takeUntil(subject)
  .subscribe(t => {
  console.log('pushing new item');
  this.activeItems[0].contentLeaving = true;
  setTimeout(()=>{
    this.activeItems[0].imageLeaving = true;
    setTimeout(()=>{
      this.activeItems.push(this.activeItems.shift());
      setTimeout(()=>{
        this.activeItems[1].contentLeaving = false;
        this.activeItems[1].imageLeaving = false;
      },510);
    },510);
  },510);
});
this.moduleProps.intervals.push(subject);

在我的ngOnDestroy

this.moduleProps.intervals.forEach((i)=>{
  i.complete();
});

但发生这种情况后,我仍然看到控制台日志语句显示“推送新项目”,就好像它仍在我的时间间隔内运行一样。

【问题讨论】:

  • 您可以在subscribe() 中调用subscription.unsubcscribe()。或者我不明白你想做什么......

标签: angular rxjs intervals


【解决方案1】:

根据本文档 (https://www.learnrxjs.io/operators/filtering/takeuntil.html),takeUntil 会发出直到提供的 observable 发出。你正在完成 observable 而不发射任何东西。尝试将 .next() 添加到您的 onDestroy 方法中。

this.moduleProps.intervals.forEach((i)=>{
  i.next(); // have subject emit
  i.complete();
});

这是一个有效的 plunk (https://plnkr.co/edit/Zdf8C9d8vHk84uIMYHvH?p=preview)

【讨论】:

  • 我也试过了,也让.next()传回一些东西,间隔继续。
  • @Jordan,你能不能只存储你的间隔订阅,然后在你的 ngOnDestroy 中取消订阅以停止间隔。而不是使用 takeUntil 运算符
  • 我也试过了,还是不行。有趣的是,如果我在超时设置后立即尝试调用.next().compelte(),一切正常。当我稍后尝试使用参考时,它才不起作用
  • @Jordan 你确定正在触发 ngOnDestroy 方法吗?
【解决方案2】:

尝试用.takeWhile 代替.takeUntil,它可以使用布尔值。

private finished = false;  // component property

var interval = Observable.interval(this.settings.timing * 1000);
var subscription = interval
  .takeWhile(_ => this.finished)
  .subscribe(t => {
  ...

OnDestroy 就是 this.finished = true;

【讨论】:

  • takeWhile 接受一个假定返回布尔值的函数,而不仅仅是一个布尔值
猜你喜欢
  • 1970-01-01
  • 2016-05-02
  • 2017-12-24
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
相关资源
最近更新 更多