EffectImpl constructor

EffectImpl(
  1. void fn(), {
  2. bool lazy = false,
  3. JoltDebugFn? onDebug,
})

Creates a new effect with the given function.

Parameters:

  • fn: The effect function to execute
  • lazy: Whether to run the effect immediately upon creation. If true, the effect will execute once immediately when created, then automatically re-run whenever its reactive dependencies change. If false (default), the effect will only run when dependencies change, not immediately upon creation.
  • onDebug: Optional debug callback for reactive system debugging

The effect function will be called immediately upon creation (if lazy is true) and then automatically whenever any of its reactive dependencies change.

Example:

final signal = Signal(0);

// Effect runs immediately and whenever signal changes
final effect = Effect(() {
  print('Signal value: ${signal.value}');
}, lazy: true);

// Effect only runs when signal changes (not immediately)
final delayedEffect = Effect(() {
  print('Signal value: ${signal.value}');
}, lazy: false);

signal.value = 1; // Both effects run

Implementation

EffectImpl(this.fn, {bool lazy = false, JoltDebugFn? onDebug})
    : super(flags: ReactiveFlags.watching | ReactiveFlags.recursedCheck) {
  JoltDebug.create(this, onDebug);

  final prevSub = getActiveSub();
  if (prevSub != null) {
    link(this, prevSub, 0);
  }

  if (!lazy) {
    final prevSub = setActiveSub(this);
    try {
      _effectFn();
    } finally {
      setActiveSub(prevSub);
      flags &= ~ReactiveFlags.recursedCheck;
    }
  } else {
    flags &= ~ReactiveFlags.recursedCheck;
  }
}