manidos
manidos

Reputation: 3464

How to detect change in a variable?

I have a variable in global scope that I need to check periodically for changes. This is how I would do it in simple JS:

    let currentValue, oldValue;

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

How is it done using Observables?

Upvotes: 7

Views: 2535

Answers (1)

Olaf Horstmann
Olaf Horstmann

Reputation: 16882

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

Or you can optionally give a comparator-function:

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

Upvotes: 8

Related Questions