Select Git revision
computation.ts
computation.ts 9.26 KiB
/**
* Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* Adapted from https://github.com/dsehnal/LiteMol
* @author David Sehnal <david.sehnal@gmail.com>
*/
import Scheduler from './scheduler'
import timeNow from './time'
interface Computation<A> {
(ctx?: Computation.Context): Promise<A>
}
namespace Computation {
export let PRINT_ERRORS_TO_CONSOLE = false;
export function create<A>(computation: (ctx: Context) => Promise<A>) {
return ComputationImpl(computation);
}
export function resolve<A>(a: A) {
return create<A>(_ => Promise.resolve(a));
}
export function reject<A>(reason: any) {
return create<A>(_ => Promise.reject(reason));
}
export interface Params {
updateRateMs?: number,
observer?: ProgressObserver
}
export const Aborted = 'Aborted';
export interface Progress {
message: string,
isIndeterminate: boolean,
current: number,
max: number,
elapsedMs: number,
requestAbort?: () => void
}
export interface ProgressUpdate {
message?: string,
abort?: boolean | (() => void),
current?: number,
max?: number
}
export interface Context {
readonly isSynchronous: boolean,
/** Also checks if the computation was aborted. If so, throws. */
readonly requiresUpdate: boolean,
requestAbort(): void,
subscribe(onProgress: ProgressObserver): { dispose: () => void },
/** Also checks if the computation was aborted. If so, throws. */
update(info: ProgressUpdate): Promise<void> | void
}
export type ProgressObserver = (progress: Readonly<Progress>) => void;
const emptyDisposer = { dispose: () => { } }
/** A context without updates. */
export const synchronous: Context = {
isSynchronous: true,