Delay an Observable pipe until an external condition is met, such as a property being populated on a global object.
ngOnInit() {
const isIdTokenPopulated = () => !!(this.account.idToken);
// Create a notifier Observable that emits when the property is populated (as signaled by an event that gets dispatched)
const propertyPopulated$ = fromEvent(document, 'ID TOKEN HAS BEEN POPULATED').pipe(
filter(isIdTokenPopulated),
take(1)
);
let intervalId = setInterval(() => {
console.log('%c' + `checking for idToken..........`, 'background-color:cyan');
if(isIdTokenPopulated()){
clearInterval(intervalId);
console.log('%c' + `idToken populated!`, 'background-color:pink');
document.dispatchEvent(new Event('ID TOKEN HAS BEEN POPULATED'));
}
}, 50);
someObservable$.pipe(
tap(x => console.log('%c' + `waiting for idToken to be populated (${(new Date()).toString()})`, 'background-color:yellow')),
delayWhen((value, index) => propertyPopulated$),
tap(x => console.log('%c' + `idToken is populated (${(new Date()).toString()})`, 'background-color:yellow'))
).subscribe(
value => console.log('got value', value),
(err) => this.error = 'You are not authorized to use this application.',
() => this.loading = false
);
Leave a Reply