vector-im-hydrogen-web/src/utils/AbortableOperation.ts

56 lines
1.7 KiB
TypeScript
Raw Normal View History

2021-08-23 15:54:06 +02:00
/*
Copyright 2020 The Matrix.org Foundation C.I.C.
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.
*/
2023-03-21 18:24:46 +01:00
import {EventEmitter} from "../utils/EventEmitter";
2021-11-17 15:57:23 +01:00
export interface IAbortable {
2021-08-23 15:54:06 +02:00
abort();
}
export type SetAbortableFn = (a: IAbortable) => typeof a;
export type SetProgressFn<P> = (progress: P) => void;
type RunFn<T, P> = (setAbortable: SetAbortableFn, setProgress: SetProgressFn<P>) => T;
2021-08-23 15:54:06 +02:00
2023-03-21 18:24:46 +01:00
export class AbortableOperation<T, P = void> extends EventEmitter<{change: keyof AbortableOperation<T, P>}> implements IAbortable {
2021-08-23 15:54:06 +02:00
public readonly result: T;
private _abortable?: IAbortable;
2023-03-21 18:24:46 +01:00
private _progress?: P;
2021-08-23 15:54:06 +02:00
constructor(run: RunFn<T, P>) {
2023-03-21 18:24:46 +01:00
super();
this._abortable = undefined;
const setAbortable: SetAbortableFn = abortable => {
2021-08-23 15:54:06 +02:00
this._abortable = abortable;
return abortable;
};
2023-03-21 18:24:46 +01:00
this._progress = undefined;
const setProgress: SetProgressFn<P> = (progress: P) => {
2023-03-21 18:24:46 +01:00
this._progress = progress;
this.emit("change", "progress");
};
this.result = run(setAbortable, setProgress);
}
2023-03-21 18:24:46 +01:00
get progress(): P | undefined {
return this._progress;
2021-08-23 15:54:06 +02:00
}
abort() {
this._abortable?.abort();
this._abortable = undefined;
2021-08-23 15:54:06 +02:00
}
}