2020-08-05 18:38:55 +02:00
|
|
|
/*
|
|
|
|
Copyright 2020 Bruno Windels <bruno@windels.cloud>
|
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
limitations under the License.
|
|
|
|
*/
|
|
|
|
|
2020-04-09 23:19:49 +02:00
|
|
|
function disposeValue(value) {
|
2020-05-06 23:31:36 +02:00
|
|
|
if (typeof value === "function") {
|
2020-04-09 23:19:49 +02:00
|
|
|
value();
|
|
|
|
} else {
|
|
|
|
value.dispose();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export class Disposables {
|
|
|
|
constructor() {
|
|
|
|
this._disposables = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
track(disposable) {
|
2020-09-10 17:43:01 +02:00
|
|
|
if (this.isDisposed) {
|
|
|
|
throw new Error("Already disposed, check isDisposed after await if needed");
|
|
|
|
}
|
2020-04-09 23:19:49 +02:00
|
|
|
this._disposables.push(disposable);
|
2020-09-10 16:40:30 +02:00
|
|
|
return disposable;
|
2020-04-09 23:19:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
dispose() {
|
|
|
|
if (this._disposables) {
|
|
|
|
for (const d of this._disposables) {
|
|
|
|
disposeValue(d);
|
|
|
|
}
|
|
|
|
this._disposables = null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-10 17:43:01 +02:00
|
|
|
get isDisposed() {
|
|
|
|
return this._disposables === null;
|
|
|
|
}
|
|
|
|
|
2020-04-09 23:19:49 +02:00
|
|
|
disposeTracked(value) {
|
2020-09-10 17:43:01 +02:00
|
|
|
if (value === undefined || value === null || this.isDisposed) {
|
2020-05-05 23:19:02 +02:00
|
|
|
return null;
|
|
|
|
}
|
2020-04-09 23:19:49 +02:00
|
|
|
const idx = this._disposables.indexOf(value);
|
|
|
|
if (idx !== -1) {
|
|
|
|
const [foundValue] = this._disposables.splice(idx, 1);
|
|
|
|
disposeValue(foundValue);
|
2020-05-05 23:19:02 +02:00
|
|
|
} else {
|
|
|
|
console.warn("disposable not found, did it leak?", value);
|
2020-04-09 23:19:49 +02:00
|
|
|
}
|
2020-05-05 23:19:02 +02:00
|
|
|
return null;
|
2020-04-09 23:19:49 +02:00
|
|
|
}
|
|
|
|
}
|