Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect change in a variable?

Tags:

rxjs

rxjs5

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?

like image 651
manidos Avatar asked Jan 27 '17 07:01

manidos


1 Answers

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>);
like image 55
olsn Avatar answered Oct 11 '22 02:10

olsn