Path: blob/main/components/gitpod-protocol/src/util/disposable.ts
2500 views
/*1* Copyright (C) 2017 TypeFox and others.2*3* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.4* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.05*/6import { Event, Emitter } from "./event";78export interface Disposable {9/**10* Dispose this object.11*/12dispose(): void;13}1415export namespace Disposable {16export function create(func: () => void): Disposable {17return {18dispose: func,19};20}21export const NULL = create(() => {});22}2324export class DisposableCollection implements Disposable {25protected readonly disposables: Disposable[] = [];26protected readonly onDisposeEmitter = new Emitter<void>();2728get onDispose(): Event<void> {29return this.onDisposeEmitter.event;30}3132protected checkDisposed(): void {33if (this.disposed) {34this.onDisposeEmitter.fire(undefined);35}36}3738get disposed(): boolean {39return this.disposables.length === 0;40}4142dispose(): void {43if (this.disposed) {44return;45}46while (!this.disposed) {47this.disposables.pop()!.dispose();48}49this.checkDisposed();50}5152push(disposable: Disposable): Disposable {53const disposables = this.disposables;54disposables.push(disposable);55const originalDispose = disposable.dispose.bind(disposable);56const toRemove = Disposable.create(() => {57const index = disposables.indexOf(disposable);58if (index !== -1) {59disposables.splice(index, 1);60}61this.checkDisposed();62});63disposable.dispose = () => {64toRemove.dispose();65originalDispose();66};67return toRemove;68}6970pushAll(disposables: Disposable[]): Disposable[] {71return disposables.map((disposable) => this.push(disposable));72}73}747576