2017-10-05 117 views
0

我已經嘗試過幾乎所有可以找到的東西,並且似乎無法獲取此間隔以停止執行訂閱中的代碼。我使用間隔錯誤?不能停止可觀察間隔

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

但畢竟這發生了,我仍然看到控制檯日誌聲明,稱「推新項目」,如果它仍然在我的區間運行。

+0

你可以叫'subscription.unsubcscribe()''內部認購()'。或者,也許我不明白你想要做什麼... – martin

回答

0

根據本文檔(https://www.learnrxjs.io/operators/filtering/takeuntil.html),takeUntil發射直到提供的observable發射。你正在完成觀察而不發射任何東西。嘗試將.next()添加到您的onDestroy方法中。

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

這裏是一個工作普拉克(https://plnkr.co/edit/Zdf8C9d8vHk84uIMYHvH?p=preview

+0

我也試過,也有'.next()'傳遞回來的東西,間隔繼續下去。 – Jordan

+1

@Jordan,你可以只存儲你的間隔訂閱,然後在你的ngOnDestroy取消訂閱那些停止時間間隔。而不是使用takeUntil運算符 – LLai

+0

我也試過,它也不起作用。有趣的是,如果我在超時之後立即調用'.next()'和'.compelte()',它將完全正常工作。只有當我嘗試稍後使用引用時,它纔會起作用 – Jordan

0

嘗試.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;

+0

takeWhile接受一個函數,假設返回一個布爾值,而不僅僅是一個布爾值 – LLai

+0

確實,正在糾正...... –