# HG changeset patch # User cin # Date 2018-09-10 22:23:22 # Node ID b8fc13e5c702f977d4fd4e33b1dd235ed367b5f4 # Parent 638c2fe3453120fb4ae454f403d54e5b33f33a7e working on core/Cancellation diff --git a/src/ts/Cancellation.ts b/src/ts/Cancellation.ts --- a/src/ts/Cancellation.ts +++ b/src/ts/Cancellation.ts @@ -1,33 +1,67 @@ import { ICancellation } from "./interfaces"; +import { argumentNotNull } from "./safe"; export class Cancellation implements ICancellation { + private _reason: any; + private _cbs: Array<(e) => void>; + + constructor(action: (cancel: (e) => void) => void) { + argumentNotNull(action, "action"); + + action(this._cancel.bind(this)); + } + isSupported(): boolean { - return false; + return true; } throwIfRequested(): void { + if (this._reason) + throw this._reason; } - + isRequested(): boolean { - return false; + return !!this._reason; } - register(_cb: (e:any) => void): void { - + register(cb: (e: any) => void): void { + argumentNotNull(cb, "cb"); + + if (this._reason) { + cb(this._reason); + } else { + if (!this._cbs) + this._cbs = [cb]; + else + this._cbs.push(cb); + } } - static readonly none : Cancellation = { + private _cancel(reason) { + if (this._reason) + return; + + this._reason = (reason = reason || new Error("Operation cancelled")); + + + if (this._cbs) { + this._cbs.forEach(cb => cb(reason)); + this._cbs = null; + } + } + + static readonly none: ICancellation = { isSupported(): boolean { return false; }, throwIfRequested(): void { }, - + isRequested(): boolean { return false; }, - - register(_cb: (e:any) => void): void { + + register(_cb: (e: any) => void): void { } }; } \ No newline at end of file