Cancellation.ts
88 lines
| 1.9 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r18 | import { ICancellation, IDestroyable } from "./interfaces"; | ||
|
|
r17 | import { argumentNotNull } from "./safe"; | ||
|
|
r13 | |||
|
|
r18 | const destroyed = { | ||
| destroy() { | ||||
| } | ||||
| }; | ||||
|
|
r13 | export class Cancellation implements ICancellation { | ||
|
|
r17 | private _reason: any; | ||
| private _cbs: Array<(e) => void>; | ||||
| constructor(action: (cancel: (e) => void) => void) { | ||||
| argumentNotNull(action, "action"); | ||||
| action(this._cancel.bind(this)); | ||||
| } | ||||
|
|
r13 | isSupported(): boolean { | ||
|
|
r17 | return true; | ||
|
|
r13 | } | ||
| throwIfRequested(): void { | ||||
|
|
r17 | if (this._reason) | ||
| throw this._reason; | ||||
|
|
r13 | } | ||
|
|
r17 | |||
|
|
r13 | isRequested(): boolean { | ||
|
|
r17 | return !!this._reason; | ||
|
|
r13 | } | ||
|
|
r18 | register(cb: (e: any) => void): IDestroyable { | ||
|
|
r17 | argumentNotNull(cb, "cb"); | ||
| if (this._reason) { | ||||
| cb(this._reason); | ||||
|
|
r18 | return destroyed; | ||
|
|
r17 | } else { | ||
| if (!this._cbs) | ||||
| this._cbs = [cb]; | ||||
| else | ||||
| this._cbs.push(cb); | ||||
|
|
r18 | |||
|
|
r39 | const me = this; | ||
|
|
r18 | return { | ||
|
|
r39 | destroy() { | ||
| me._unregister(cb); | ||||
| } | ||||
|
|
r18 | }; | ||
|
|
r17 | } | ||
|
|
r13 | } | ||
|
|
r39 | |||
|
|
r18 | private _unregister(cb) { | ||
|
|
r39 | if (this._cbs) { | ||
| const i = this._cbs.indexOf(cb); | ||||
| if (i >= 0) | ||||
| this._cbs.splice(i, 1); | ||||
| } | ||||
|
|
r18 | } | ||
|
|
r13 | |||
|
|
r17 | 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 = { | ||||
|
|
r13 | isSupported(): boolean { | ||
| return false; | ||||
| }, | ||||
| throwIfRequested(): void { | ||||
| }, | ||||
|
|
r17 | |||
|
|
r13 | isRequested(): boolean { | ||
| return false; | ||||
| }, | ||||
|
|
r17 | |||
|
|
r18 | register(_cb: (e: any) => void): IDestroyable { | ||
|
|
r39 | return destroyed; | ||
|
|
r13 | } | ||
| }; | ||||
|
|
r39 | } | ||
