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>
+3
source to share