import { EventSource } from '../Events/EventSource' ; export class AsyncLazy < T > { private valueCreated = new EventSource ( ) ; private isValueCreated = false ; private isCreatingValue = false ; private value : T | undefined ; constructor ( private valueFactory ) { } public setValueFactory ( valueFactory ) { this . valueFactory = valueFactory ; } public async getValue ( ) { if ( this . isValueCreated ) { return Promise . resolve ( this . value ) ; } if ( this . isCreatingValue ) { return new Promise < T > ( ( resolve ) => { this . valueCreated . on ( ( ) => resolve ( this . value ) ) ; } ) ; } this . isCreatingValue = true ; this . value = await this . valueFactory ( ) ; this . isCreatingValue = false ; this . isValueCreated = true ; this . valueCreated . notify ( null ) ; return Promise . resolve ( this . value ) ; } }