lifecycle-utils
    Preparing search index...

    Function registerFinalizer

    • Register a finalizer for a given target, so that the finalizer is called after the target is garbage-collected.

      A finalizer can be a function to call, an object with a dispose method, an object with a Symbol.dispose method, an object with a Symbol.asyncDispose method, or a Promise that resolves to one of the previous types.

      When registering a finalizer, the result is a handle that can be used to dispose the registration (so that the finalizer won't trigger when the object is garbage-collected).

      You can register multiple finalizers for the same target, and each registration is completely separate.

      Note: make sure to never reference the target in the finalizer, since otherwise it might cause the target to never get garbage-collected.

      Parameters

      Returns FinalizerRegistrationHandle

      import {DisposeAggregator, registerFinalizer} from "lifecycle-utils";

      const disposeAggregator = new DisposeAggregator();
      disposeAggregator.add(() => console.log("disposed"));

      let obj: {} | null = {};
      registerFinalizer(obj, disposeAggregator);

      obj = null; // get rid of a reference to the object
      await new Promise((accept) => setTimeout(accept, 1000 * 10)); // wait for the garbage collector

      // disposed
      import {registerFinalizer} from "lifecycle-utils";

      let disposed1 = false;
      let disposed2 = false;

      let obj: {} | null = {};
      const handle1 = registerFinalizer(obj, () => {
      disposed1 = true;
      });
      const handle2 = registerFinalizer(obj, () => {
      disposed2 = true;
      });

      console.log(disposed2.finalized); // false

      handle1.dispose(); // remove the finalizer
      obj = null; // get rid of a reference to the object

      await new Promise((accept) => setTimeout(accept, 1000 * 10)); // wait for the garbage collector

      console.log(disposed1); // false, because we removed the finalizer
      console.log(disposed2); // true

      console.log(disposed2.finalized); // true