EffectImpl constructor

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

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.
  • debug: Optional debug options

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, JoltDebugOption? debug})
    : super(flags: ReactiveFlags.watching | ReactiveFlags.recursedCheck) {
  JoltDebug.create(this, debug);

  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;
  }
}