[英]Cancel previous observable returned from another function
我有一種情況,如果返回新的 observable,我需要取消以前的 observable。 見下文
function fooService(timeOut: number): Observable<string> {
return new Observable(subs => {
setTimeout(() => {
subs.next(new Date().toTimeString());
}, timeOut);
});
}
function barComponent(timeOut: number): void {
// here it should cancel previous subscription if this function called again
fooService(timeOut).subscribe(
time => console.log(time)
);
}
barComponent(5000);
barComponent(2000); // i need to cancel last call
您可以將可觀察訂閱保存到一個變量,然后如果它被調用一次,則調用unsubscribe
,如下所示:
let observableInstance; function fooService(timeOut: number): Observable<string> { return new Observable(subs => { setTimeout(() => { subs.next(new Date().toTimeString()); }, timeOut); }); } function barComponent(timeOut: number): void { if (observableInstance) { observableInstance.unsubscribe(); } observableInstance = fooService(timeOut).subscribe(time => console.log(time)); } barComponent(5000); barComponent(2000);
工作堆棧閃電戰:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.