autoDispose method

Signal<T> autoDispose({
  1. void onDispose()?,
})

Configures this signal to automatically dispose when all observers are removed, returning the signal itself to allow fluent builder chaining.

Implementation

Signal<T> autoDispose({void Function()? onDispose}) {
  autoDisposeEnabled = true;
  if (onDispose != null) {
    final previousOnDispose = onDisposeCallback;
    onDisposeCallback = () {
      previousOnDispose?.call();
      onDispose();
    };
  }
  // If it currently has no observers, dispose immediately
  if (observers.isEmpty && !isDisposed) {
    dispose();
  }
  return this;
}