I'm trying to learn reactive programming. I'm simulating the change of a boolean variable in time. The idea is that, I wouldn't know when it is going to change, but I want the app to execute a console.log saying that the variable is true, each time it changes from false
to true
. I did this:
let x = false
setInterval(function(){
x = !x;
}, 3000);
I can't figure out the approach to tell the app to be watching at the x
variable's state and a fire console.log("now it's true")
each time x == true
.
What could be the simplest way to achieve it? I think I could do it using observables, however, I'm kind of stuck.
First of all, you should understand that no one uses "reactive programming" by writing it in pure js :) There are a lot of libraries, for example React, Vue, Angular, which implement reactivity.
There are base approaches on which, I think so, every reactivity implementation in JS is built on:
const obj = {
x: true,
setX(value) {
this.x = value;
// You can track x value here
},
};
obj.setX(false);
const obj = {
_x: 5,
get x() {
return this._x;
},
set x(value) {
this._x = value;
// You can track x value here
},
};
obj.x = 6;