Logosolidart

Effect API docs

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 Effect. The effect subscribes automatically to any signal used in the callback and reruns when any of them change.

Constructor#

Effect(
  void Function(DisposeEffect dispose) callback, {
    ErrorCallback? onError,
    EffectOptions options = const EffectOptions(),
  }
);

callback is the function used to run the effect and tracks all the signals used.

onError is an optional callback that is called when the effect throws an error. By default the effect error is thrown but with onError you can gracefully handle it.

options are the options of the effect.

final count = Signal(1);
Effect((_) {
  print('The count is ${count.value}');
});
// prints "The count is 1"
count.value++;
// prints "The count is 2"
An effect runs immediately when created.

bool get disposed#

Returns true if the effect has been disposed.

void dispose()#

Disposes the effect. If the effect has already been disposed, this method does nothing.

Removes the subscriber from all the tracked signals.

final count = Signal(0);
final effect = Effect((_) {
  print("The count is ${count.value}");
});
effect.dispose(); // disposes the effect

void call()#

Disposes the effect, like above.

final count = Signal(0);
final disposeEffect = Effect((_) {
  print("The count is ${count.value}");
});
disposeEffect(); // disposes the effect

AnEffect only tracks the current dependencies.

final name = Signal("John");
final lastName = Signal("Doe");
final showFullName = Signal(false);

Effect((_) {
  if (showFullName()) {
    print("${name.value} ${lastName.value}");
  } else {
    print(name.value);
  }
});

In the case above the Effect prints John because showFullName is false. If you try to change the lastName to Smith, the effect won't react because is not tracking lastName.

If you set showFullName to true, the effect will print John Doe and will track all the signals: showFullName, name and lastName.

Use conditional logic carefully when using Effect.