Effects
Signals are trackable values, but they are only one half of the equation. To complement those are observers that can be updated by those trackable values. An effect is one such observer; it runs a side effect that depends on signals.
An effect can be created by using createEffect
.
The effect subscribes to any signal provided in the signals array and reruns when any of them change.
So let's create an Effect
that reruns whenever counter
changes:
// sample signal
final counter = createSignal(0);
// effect creation
createEffect(() {
print("The count is now ${counter.value}");
}, signals: [counter]);
// increment the counter
counter.value++;
// The effect prints `The count is now 1`;
The effect automatically cancels when all the
signals
provided disposeThe createEffect
method returns an Effect
class giving you a more advanced usage:
final effect = createEffect(() {
print("The count is now ${counter.value}");
}, signals: [counter], fireImmediately: true);
print(effect.isRunning); // prints true
// pause effect
effect.pause();
print(effect.isPaused); // prints true
// resume effect
effect.resume();
print(effect.isResumed); // prints true
// cancel effect
effect.cancel();
print(effect.isCancelled); // prints true
The fireImmediately
flag indicates if the effect should run immediately with the current signals
values, defaults to false.
You may want to pause
, resume
or cancel
an effect.
An effect is useless after it is cancelled, you must not use it anymore.