Proximo Proximo - 5 months ago 179
Node.js Question

RxJs How to Observe object property change

I'm running into an issue. I have a client that instantiates but has a ready Boolean property. I want to wait until it switches to true then resolve a promise. I tried a lot of different ways including while loop to just blocking the thread completely without checking for updates.

Here's that attempt

var startClient = function() { return new Promise((resolve, reject)=> {
var client = CreateClient();
while(!client.ready) {}
resolve(client);
});
};


My question is: Is there a way to use RxJs to help.. Maybe emit and event if the ready property is changed? Below is more pseudo code for what I'm trying to do.

var startClient = function() { return new Promise((resolve, reject)=> {
var client = CreateClient();
var emitter = Observable.watch(client, 'ready');
emitter.on('ready', function(result) {
if(result) resolve(client);
});
};


Any suggestions? Thanks!

Answer

If you can, you could overwrite the ready property on the client to trap assignments to it, as follows:

// Check if the ready flag is already set.
if (client.ready) return resolve(client);

let _ready;
Object.defineProperty(client, 'ready', {

  // Trap an assignment and resolve if true.
  set(b) { _ready = b; if (b) resolve(client); },

  // Politely provider a getter in case someone else is trying to access it.
  get()  { return _ready; }

});

This won't work if the property is not configurable, or the object is frozen, etc.

Comments