packageDocumentation module public export interface IDisposable { note dispose ( ) : void ; } public export function isIDisposable ( obj ) { return ! ! obj && ( obj instanceof Object ) && ! ! ( obj as IDisposable ) . dispose && ( typeof ( obj as IDisposable ) . dispose === "function" ) ; } param disposable returns public export function dispose ( disposable ? ) { if ( undefined !== disposable ) disposable . dispose ( ) ; return undefined ; } param list returns public export function disposeArray ( list ? ) { if ( undefined === list ) return undefined ; for ( const entry of list ) dispose ( entry ) ; list . length = 0 ; return undefined ; } public export function using < T extends IDisposable , TResult > ( resources , func ) { if ( ! Array . isArray ( resources ) ) return using ( [ resources ] , func ) ; const doDispose = ( ) => resources . forEach ( ( disposable ) => disposable . dispose ( ) ) ; let shouldDisposeImmediately = true ; try { const result = func ( ... resources ) ; if ( result instanceof Promise ) { shouldDisposeImmediately = false ; result . then ( doDispose , doDispose ) ; } return result ; } finally { if ( shouldDisposeImmediately ) doDispose ( ) ; } } public export type DisposeFunc = ( ) => void ; class FuncDisposable implements IDisposable { private _disposeFunc : ( ) => void ; constructor ( disposeFunc ) { this . _disposeFunc = disposeFunc ; } public dispose ( ) { this . _disposeFunc ( ) ; } } public export class DisposableList implements IDisposable { private _disposables : IDisposable [ ] ; /** Creates a disposable list. */ constructor ( disposables = [ ] ) { this . _disposables = [ ] ; disposables . forEach ( ( disposable ) => { this . add ( disposable ) ; } ) ; } private isDisposable ( x ) { return ( x as IDisposable ) . dispose !== undefined ; } /** Register an object for disposal. */ public add ( disposable ) { if ( this . isDisposable ( disposable ) ) this . _disposables . push ( disposable ) ; else this . _disposables . push ( new FuncDisposable ( disposable ) ) ; } /** Unregister disposable object. */ public remove ( disposable ) { const idx = this . _disposables . indexOf ( disposable ) ; if ( - 1 !== idx ) this . _disposables . splice ( idx , 1 ) ; } /** Disposes all registered objects. */ public dispose ( ) { for ( const disposable of this . _disposables ) disposable . dispose ( ) ; } }