willDispose<T> method

  1. @nonVirtual
T willDispose<T>(
  1. T resource, {
  2. _OnBeforeCallback<T>? onBeforeDispose,
})
inherited

Marks the resource for dispose.

This allows you to mark resources for dispose at the time of their definition within the class, making your code more concise.

You can optionally provide an onBeforeDispose callback to be called immediately before dispose.

The resource must have a dispose method. If the resource does not, a NoDisposeMethodDebugError will be thrown in kDebugMode.

Returns the resource back to allow for easy chaining or assignment.

Implementation

@nonVirtual
T willDispose<T>(T resource, {_OnBeforeCallback<T>? onBeforeDispose}) {
  // Verify that the resource has a dispose method in debug mode.
  _verifyDisposeMethod(resource);
  final disposable = (
    resource: resource as dynamic,
    onBeforeDispose: onBeforeDispose != null
        ? (dynamic e) => onBeforeDispose(e as T)
        : null,
  );

  // Check for any duplicate resource.
  final duplicate = _toDisposeResources
      .where((e) => e.resource == resource)
      .firstOrNull;

  if (duplicate != null) {
    if (kDebugMode) {
      // Throw an error in debug mode to inform the developer of duplicate
      // calls to `willDispose()` on the same resource.
      throw WillAlreadyDisposeDebugError(disposable);
    }
    // Remove the duplicate resource from the set.
    _toDisposeResources.remove(duplicate);
  }

  // Add the new resource to the set. If there was a duplicate, it may
  // have had a different onBeforeDispose callback. This will update it.
  _toDisposeResources.add(disposable);

  return resource;
}