How to detect a change in a variable?

I have a variable in the global scope that I should periodically check for changes. Here is how I would do it in plain JS:

    let currentValue, oldValue;

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

How to do this using Observables?

+6
source share
1 answer
Observable.interval(1000)
    .map(() => currentValue)
    .distinctUntilChanged();

Or you can specify a comparator function:

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

Source: https://habr.com/ru/post/1014485/


All Articles