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-01-20 16:17:22 +01:00
|
|
|
import {BaseObservableValue, ObservableValue} from "../observable/value";
|
2022-01-26 15:18:23 +01:00
|
|
|
|
2021-11-17 20:27:23 +05:30
|
|
|
export interface IAbortable {
|
2021-08-23 15:54:06 +02:00
|
|
|
abort();
|
|
|
|
}
|
|
|
|
|
2022-01-26 15:18:23 +01:00
|
|
|
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
|
|
|
|
2022-01-26 15:18:23 +01:00
|
|
|
export class AbortableOperation<T, P = void> implements IAbortable {
|
2021-08-23 15:54:06 +02:00
|
|
|
public readonly result: T;
|
2022-01-26 15:18:23 +01:00
|
|
|
private _abortable?: IAbortable;
|
|
|
|
private _progress: ObservableValue<P | undefined>;
|
2021-08-23 15:54:06 +02:00
|
|
|
|
2022-01-26 15:18:23 +01:00
|
|
|
constructor(run: RunFn<T, P>) {
|
|
|
|
this._abortable = undefined;
|
|
|
|
const setAbortable: SetAbortableFn = abortable => {
|
2021-08-23 15:54:06 +02:00
|
|
|
this._abortable = abortable;
|
|
|
|
return abortable;
|
|
|
|
};
|
2022-01-26 15:18:23 +01:00
|
|
|
this._progress = new ObservableValue<P | undefined>(undefined);
|
|
|
|
const setProgress: SetProgressFn<P> = (progress: P) => {
|
|
|
|
this._progress.set(progress);
|
|
|
|
};
|
|
|
|
this.result = run(setAbortable, setProgress);
|
|
|
|
}
|
|
|
|
|
|
|
|
get progress(): BaseObservableValue<P | undefined> {
|
|
|
|
return this._progress;
|
2021-08-23 15:54:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
abort() {
|
|
|
|
this._abortable?.abort();
|
2022-01-26 15:18:23 +01:00
|
|
|
this._abortable = undefined;
|
2021-08-23 15:54:06 +02:00
|
|
|
}
|
|
|
|
}
|