effect function

Effect effect(
  1. BuildContext? context,
  2. void callback(), {
  3. bool detach = false,
  4. String? debugLabel,
  5. Object? debugOwner,
  6. String? debugScope,
  7. String? debugType,
  8. String? debugNote,
})

Creates a reactive effect that automatically tracks its dependencies and re-runs when they change.

An effect is a reactive computation that automatically tracks any reactive values (signals or computed values) accessed during its execution. The effect will re-run whenever any of its tracked dependencies change.

The run function will be executed:

  1. Immediately when the effect is created
  2. Whenever any of its tracked dependencies change

Returns a cleanup function that can be called to dispose of the effect and stop tracking.

Example:

final count = signal(context, 0);
final stop = effect(context, () {
  print(count());
}); // Print 0

count.set(1); // Print 1

stop();
count.set(2); // No output

Implementation

alien.Effect effect(
  BuildContext? context,
  void Function() callback, {
  bool detach = false,
  String? debugLabel,
  Object? debugOwner,
  String? debugScope,
  String? debugType,
  String? debugNote,
}) {
  if (context == null) {
    return _createEffect(
      callback: callback,
      detach: detach,
      debugLabel: debugLabel,
      debugOwner: debugOwner,
      debugScope: debugScope,
      debugType: debugType,
      debugNote: debugNote,
    );
  }

  final e = useMemoized(context, () {
    if (detach || alien.getActiveSub() != null) {
      return _createEffect(
        context: context,
        callback: callback,
        detach: detach,
        debugLabel: debugLabel,
        debugOwner: debugOwner,
        debugScope: debugScope,
        debugType: debugType,
        debugNote: debugNote,
      );
    }

    final scope = useWidgetScope(context);
    final prevSub = alien.setActiveSub(scope as alien.ReactiveNode);
    try {
      return _createEffect(
        context: context,
        callback: callback,
        detach: false,
        debugLabel: debugLabel,
        debugOwner: debugOwner,
        debugScope: debugScope,
        debugType: debugType,
        debugNote: debugNote,
      );
    } finally {
      alien.setActiveSub(prevSub);
    }
  });

  assert(() {
    e.callback = _wrapEffectCallback(() => e, callback);
    return true;
  }());

  return e;
}