简体   繁体   English

为什么Observable.create()中的setInterval()继续运行?

[英]Why setInterval() inside Observable.create() keeps on running?

I'm studying rxjs Observables and I couldn't understand why the setInterval inside Observable.create is still running even I have unsubscribe to that observable object. 我正在研究rxjs Observables,即使我取消订阅该Observable对象,也无法理解为什么Observable.create中的setInterval仍在运行。 Observable is async right? 可以观察到异步吗? When it supposed to stop? 它什么时候应该停止?

I have this code for reference: 我有以下代码供参考:

var cancellableObserver = Observable.create((observer:any)=>{
try {
    observer.next("anyeong")
    observer.next("ande")
    console.log("logged once")
    setInterval(()=>{
        //this code block will keep running for every 2secs
        observer.next("eotteokke") //but this line will stop after unsubscribe
        console.log("will log every 2secs")
    },2000)
} catch (err) {
    observer.error(err);

}});

var cancellableSubscription = cancellableObserver.subscribe(
(x:any) =>addItem(x),
(err:any) =>addItem(err),
() => addItem("cancellable completed"));

setTimeout(() => {cancellableSubscription.unsubscribe();console.log("mary");}, 6001);

setInterval is scheduled by JavaScript's runtime. setInterval由JavaScript的运行时安排。 When you unsubscribe from an Observable that called setInterval no-one tells the runtime to cancel the scheduled action. 取消订阅名为setInterval的Observable时,没有人告诉运行时取消计划的操作。 You might actually want to keep the interval running in some use-cases. 您实际上可能希望在某些用例中保持间隔运行。

So instead you have to call clearInterval yourself on unsubscription that you return from the Observable 's callback: 因此,您必须在从Observable的回调返回的退订中自己调用clearInterval

const source$ = new Observable(observer => {
  const handler = setInterval(...);

  ...

  return () => clearInterval(handler);
});

setInterval is not dependent on your observable, it will continue running until you clear it by using the clearInterval() function. setInterval不依赖于您的可观察对象,它将继续运行,直到您使用clearInterval()函数将其清除为止。 To clear the interval, you have to use the returned intervalID (which is returned from setInterval() ). 要清除间隔,您必须使用返回的intervalID (从setInterval()返回)。

Examples: 例子:

// Assigning an intervalID to a variable
const intervalID = setInterval(() => {
 // Do some stuff here...
}, 2000);
// Clearing an interval
clearInterval(intervalID);

Source and further information 来源和更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM