Create observable RxJs based on method availability

I would like to wait for a method to be available before executing using RxJs observables and TypeScript inside an Angular 4 app.

So far I have come up with the use interval

in conjunction with skipWhile

, but I was wondering what is a better way to just "watch" the way it is available rather than looking every 100ms ?

 Observable
    .interval(100)
    .skipWhile(() => myObject.myFunction == null)
    .first()
    .subscribe(() => myObject.myFunction());

      

I'm new to Observable, so any understanding is appreciated!

// create element without sayHello function
const myElement = {};

// add method sayHello after 1000ms that show an alert
setTimeout(() => myElement.sayHello = () => alert('Hello'), 1000);

// watch every 100ms if sayHello function exist before to execute it
Rx.Observable
  .interval(100)
  .skipWhile((interval) => {
    const isUndefined = myElement.sayHello == null;
    write(interval, isUndefined);
    return isUndefined;
  })
  .first()
  .subscribe(() => myElement.sayHello());

// function to write result to DOM
const write = (interval, isUndefined) => {
  const node = document.createElement("DIV");
  const textnode = document.createTextNode('interval #' + interval.toString() + ' - sayHello is ' + (isUndefined ? 'UNDEFINED' : 'DEFINED'));
  node.appendChild(textnode);
  document.body.appendChild(node);
};
      

<script src="https://npmcdn.com/@reactivex/rxjs@5.0.0-beta.8/dist/global/Rx.umd.js"></script>
      

Run codeHide result


+3


source to share


1 answer


If you need to poll, you can't do much better than that. The correct reactive way would be to myObject

emit an event when the method is ready and you've subscribed to it.



0


source







All Articles