Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/gitpod-protocol/src/util/disposable.ts
2500 views
1
/*
2
* Copyright (C) 2017 TypeFox and others.
3
*
4
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
5
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
*/
7
import { Event, Emitter } from "./event";
8
9
export interface Disposable {
10
/**
11
* Dispose this object.
12
*/
13
dispose(): void;
14
}
15
16
export namespace Disposable {
17
export function create(func: () => void): Disposable {
18
return {
19
dispose: func,
20
};
21
}
22
export const NULL = create(() => {});
23
}
24
25
export class DisposableCollection implements Disposable {
26
protected readonly disposables: Disposable[] = [];
27
protected readonly onDisposeEmitter = new Emitter<void>();
28
29
get onDispose(): Event<void> {
30
return this.onDisposeEmitter.event;
31
}
32
33
protected checkDisposed(): void {
34
if (this.disposed) {
35
this.onDisposeEmitter.fire(undefined);
36
}
37
}
38
39
get disposed(): boolean {
40
return this.disposables.length === 0;
41
}
42
43
dispose(): void {
44
if (this.disposed) {
45
return;
46
}
47
while (!this.disposed) {
48
this.disposables.pop()!.dispose();
49
}
50
this.checkDisposed();
51
}
52
53
push(disposable: Disposable): Disposable {
54
const disposables = this.disposables;
55
disposables.push(disposable);
56
const originalDispose = disposable.dispose.bind(disposable);
57
const toRemove = Disposable.create(() => {
58
const index = disposables.indexOf(disposable);
59
if (index !== -1) {
60
disposables.splice(index, 1);
61
}
62
this.checkDisposed();
63
});
64
disposable.dispose = () => {
65
toRemove.dispose();
66
originalDispose();
67
};
68
return toRemove;
69
}
70
71
pushAll(disposables: Disposable[]): Disposable[] {
72
return disposables.map((disposable) => this.push(disposable));
73
}
74
}
75
76