EffectImpl constructor
EffectImpl(
- void fn(), {
- bool lazy = false,
- bool? detach,
- JoltDebugOption? debug,
Creates a new effect with the given function.
Parameters:
fn: The effect function to executelazy: Whether to defer running the effect on creation. Iftrue, the effect will NOT run immediately and will not track dependencies until you call run. Iffalse(default), the effect runs immediately on creation and then automatically re-runs whenever its reactive dependencies change.detach: If true, the effect will not be bound to the current scope and will not be disposed when the scope is disposed.debug: Optional debug options
The effect function will be called immediately upon creation (if lazy is false)
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: false);
// Effect does not run until manually triggered
final delayedEffect = Effect(() {
print('Signal value: ${signal.value}');
}, lazy: true);
signal.value = 1; // Only the immediate effect runs
Implementation
EffectImpl(this.fn, {bool lazy = false, bool? detach, JoltDebugOption? debug})
: super(flags: ReactiveFlags.watching | ReactiveFlags.recursedCheck) {
assert(() {
JoltDebug.create(this, debug);
return true;
}());
if (!(detach ?? false)) {
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;
}
}