effect function

EffectStop<Effect> effect(
  1. void fn()
)

Creates a new effect that automatically runs when its dependencies change.

An effect is a side-effect that runs immediately and then re-runs whenever any of the signals it accesses are modified. Effects are useful for performing tasks like DOM updates, logging, or making API calls in response to state changes.

Returns an EffectStop that can be used to stop the effect from running.

Example:

final count = signal(0);
final stop = effect(() {
  print('Count changed to: ${count()}');
}); // Prints: Count changed to: 0

count(1); // Prints: Count changed to: 1
count(2); // Prints: Count changed to: 2

stop(); // Effect is stopped and won't run anymore
count(3); // Nothing prints

Implementation

EffectStop<Effect> effect(void Function() fn) {
  final effect = _Effect(fn);
  if (system.activeSub != null) {
    system.link(effect, system.activeSub!);
  } else if (system.activeScope != null) {
    system.link(effect, system.activeScope!);
  }
  system.runEffect(effect);
  return EffectStop(effect);
}