core3-utils

@wixc3/patterns on Github

Home > @wixc3/patterns > SafeDisposable

SafeDisposable class

Adds dispose-safe methods to Disposables:

Signature:

export declare class SafeDisposable extends Disposables implements IDisposable 

Extends: Disposables

Implements: IDisposable

Example

export class MyDisposable implements IDisposable {
    private disposables = new SafeDisposable(MyDisposable.name)
    dispose: () => Promise<void>;

    constructor() {
        this.disposables.add('log', () => console.log('disposed'));
        this.disposables.setTimeout(() => console.log('will be canceled upon disposal'), 1000);
        this.dispose = () => this.disposables.dispose()
    }

    async doSomething() {
        // will throw if disposed, delays disposal until done is called
        return await this.disposables.guard(async () =>{
             // do something
             return await somePromise // if dispose is called while the code awaits, new guards will throw, but actual disposal will not begin
        })
        // disposal may begin
    }
}

Constructors

Constructor Modifiers Description
[(constructor)(name)](/core3-utils/patterns.safedisposable._constructor_.html) Constructs a new instance of the `SafeDisposable` class

Properties

Property Modifiers Type Description
[isDisposed](/core3-utils/patterns.safedisposable.isdisposed.html) () => boolean returns true if the disposal process started

Methods

Method Modifiers Description
[dispose()](/core3-utils/patterns.safedisposable.dispose.html) Starts instance disposal: \*\*phase 1: disposing\*\* - isDisposed === true - guard() // will throw - guard({usedWhileDisposing:true}) // will not throw (for methods that are used in the disposal process) - all guards are awaited - disposable.dispose is awaited \*\*phase 2: disposed done\*\* - guard({usedWhileDisposing:true}) // will throw
[guard(fn, options)](/core3-utils/patterns.safedisposable.guard.html) After disposal starts, it's necessary to avoid executing some code. `guard` is used for those cases. for example: after fileRemover.dispose(), fileRemover.remove() should throw. `guard` will: - throws if disposal started/finished - delays disposal actual until the current flow is done
[guard(fn, options)](/core3-utils/patterns.safedisposable.guard_1.html)
[guard(options)](/core3-utils/patterns.safedisposable.guard_2.html)
[setInterval(fn, interval)](/core3-utils/patterns.safedisposable.setinterval.html) a disposal safe setInterval checks disposal before execution and clears the interval when the instance is disposed
[setTimeout(fn, timeout)](/core3-utils/patterns.safedisposable.settimeout.html) a disposal safe setTimeout checks disposal before execution and clears the timeout when the instance is disposed