2017-01-27 24 views
5

我有一個全局範圍的變量,我需要定期檢查變化。這是我會怎麼做簡單的JS:如何檢測變量的變化?

let currentValue, oldValue; 

    setInterval(()=>{ 
     if(currentValue != oldValue){ 
      doSomething(); 
     } 
    }, 1000) 

如何使用Observables它做了什麼?

回答

6
Observable.interval(1000) 
    .map(() => currentValue) 
    .distinctUntilChanged(); 

或者你可以選擇給一個比較功能:

Observable.interval(1000) 
    .map(() => currentValue) 
    .distinctUntilChanged((oldValue, newValue) => <return true if equal>);