hydrogen-web/src/utils/Disposables.js

72 lines
1.9 KiB
JavaScript
Raw Normal View History

2020-08-05 22:08:55 +05:30
/*
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-10 02:49:49 +05:30
function disposeValue(value) {
2020-05-07 03:01:36 +05:30
if (typeof value === "function") {
2020-04-10 02:49:49 +05:30
value();
} else {
value.dispose();
}
}
export class Disposables {
constructor() {
this._disposables = [];
}
track(disposable) {
if (this.isDisposed) {
throw new Error("Already disposed, check isDisposed after await if needed");
}
2020-04-10 02:49:49 +05:30
this._disposables.push(disposable);
2020-09-10 20:10:30 +05:30
return disposable;
2020-04-10 02:49:49 +05:30
}
untrack(disposable) {
const idx = this._disposables.indexOf(disposable);
if (idx >= 0) {
this._disposables.splice(idx, 1);
}
}
2020-04-10 02:49:49 +05:30
dispose() {
if (this._disposables) {
for (const d of this._disposables) {
disposeValue(d);
}
this._disposables = null;
}
}
get isDisposed() {
return this._disposables === null;
}
2020-04-10 02:49:49 +05:30
disposeTracked(value) {
if (value === undefined || value === null || this.isDisposed) {
return null;
}
2020-04-10 02:49:49 +05:30
const idx = this._disposables.indexOf(value);
if (idx !== -1) {
const [foundValue] = this._disposables.splice(idx, 1);
disposeValue(foundValue);
} else {
console.warn("disposable not found, did it leak?", value);
2020-04-10 02:49:49 +05:30
}
return null;
2020-04-10 02:49:49 +05:30
}
}