-
Notifications
You must be signed in to change notification settings - Fork 386
Expand file tree
/
Copy pathdisposable.ts
More file actions
56 lines (49 loc) · 1.31 KB
/
disposable.ts
File metadata and controls
56 lines (49 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export interface Disposable {
/**
* Dispose this object.
*/
dispose(): void;
}
export namespace Disposable {
export function create(func: () => void): Disposable {
return {
dispose: func
};
}
}
export class DisposableStore implements Disposable {
private isDisposed: boolean;
private readonly disposables: Set<Disposable>;
constructor() {
this.isDisposed = false;
this.disposables = new Set<Disposable>();
}
/**
* Dispose of all registered disposables and mark this object as disposed.
*
* Any future disposables added to this object will be disposed of on `add`.
*/
public dispose(): void {
if (this.isDisposed || this.disposables.size === 0) {
return;
}
try {
this.disposables.forEach(item => item.dispose());
} finally {
this.isDisposed = true;
this.disposables.clear();
}
}
public add<T extends Disposable>(t: T): T {
if (this.isDisposed) {
t.dispose();
} else {
this.disposables.add(t);
}
return t;
}
}