-1

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.

0

3 Answers 3

2

I'm new with reactive programming as well.

I'd say you are correct to use the observable. Instead of your setInterval just setting x = !x, have it do something like this

e.g. I did not run it.

private xSubject = new ReplaySubject<any> (bufferSize:1); private xReadySubject: Observable<any> = this.xSubject.asObservable(); ... // In the setInterval this.xSubject.next(!x); xReadySubject.subscribe(argX => { console.log("Value of x: " + argX }); 
Sign up to request clarification or add additional context in comments.

Comments

1

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:

  • make a wrapper, for example like this:
 const obj = { x: true, setX(value) { this.x = value; // You can track x value here }, }; obj.setX(false); 
  • using getters and setters from es5 specification, here is an example:
const obj = { _x: 5, get x() { return this._x; }, set x(value) { this._x = value; // You can track x value here }, }; obj.x = 6; 

2 Comments

could you provide me an example working snippet, please?
What did you mean? In my answer I already did it. You could paste this fragments of code in any JS playground and see the result :) If you want example to proxy, well on mdn they are exists. If you want to become a real skill programmer you should advance your skill in working with any kind of documentation.
1

I found it is working

let x = false setInterval(function(){ x = !x; console.log(x); }, 1000);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.