mutate<R> method

  1. @override
R mutate<R>(
  1. R action(), {
  2. String? label,
})
override

Runs action, then notifies every listener that state changed.

Supports both synchronous actions and asynchronous actions (returning a Future). For asynchronous actions, listeners are notified once the returned Future completes.

Returns the result of action. Optionally pass label to override the action name for Orbit.observe middleware and debug logging — e.g. mutate(() => count++) (automatically uses 'increment'). If omitted, label is automatically inferred from the calling method name. If you also override snapshot, Orbit logs exactly which fields changed.

Implementation

@override
R mutate<R>(R Function() action, {String? label}) {
  if (Orbit._isRestoring) {
    return super.mutate(action, label: label);
  }

  final before = snapshot();
  try {
    final result = super.mutate(action, label: label);
    if (result is Future) {
      return (result as Future).whenComplete(() {
        final after = snapshot();
        if (before != null && after != null) {
          Orbit._pushUndo(OrbitUndoEntry(
            store: this,
            before: before,
            after: after,
            label: label,
          ));
        }
      }) as R;
    }
    final after = snapshot();
    if (before != null && after != null) {
      Orbit._pushUndo(OrbitUndoEntry(
        store: this,
        before: before,
        after: after,
        label: label,
      ));
    }
    return result;
  } catch (error) {
    final after = snapshot();
    if (before != null && after != null) {
      Orbit._pushUndo(OrbitUndoEntry(
        store: this,
        before: before,
        after: after,
        label: label,
      ));
    }
    rethrow;
  }
}