SagaStep<T extends Object?> class

A single step in a saga with its associated compensation.

A SagaStep represents an operation that can succeed and be undone. It consists of:

  • name: A descriptive label for logging and debugging
  • execute: An async function that performs the operation
  • compensate: An async function that undoes the operation

Type parameter T: The generic type T represents the return type of execute. This value is passed directly to compensate if the step succeeds and later needs to be rolled back. This ensures type safety: you can't pass the wrong type to compensation.

Execution contract:

  • execute must be a nullary function (takes no parameters)
  • If execute throws, the step is considered failed
  • compensate receives the return value from a successful execute
  • compensate should be idempotent or at least safe to call even if partial execution occurred
  • If compensate throws, it's logged but doesn't prevent other compensations from running

Example - Database transaction:

const insertUserStep = SagaStep<int>(
  name: 'Insert User',
  execute: () async {
    final userId = await db.users.insert(userData);
    return userId;  // Returns the new user ID
  },
  compensate: (userId) async {
    // userId is type-safe - definitely an int
    await db.users.delete(userId);
  },
);

Example - API call with side effects:

const createSubscriptionStep = SagaStep<String>(
  name: 'Create Subscription',
  execute: () async {
    final subscriptionId = await api.subscriptions.create(plan: 'premium');
    return subscriptionId;  // Returns subscription ID
  },
  compensate: (subscriptionId) async {
    // subscriptionId is type-safe - definitely a String
    await api.subscriptions.cancel(subscriptionId);
  },
);
Annotations
  • @experimental

Constructors

SagaStep({required String name, required Future<T> execute(), required Future<void> compensate(T)})
Creates a saga step with the given name, execute, and compensate functions.
const

Properties

compensate Future<void> Function(T)
Compensates (rolls back) a successful execution.
final
execute Future<T> Function()
Executes the operation for this step.
final
hashCode int
The hash code for this object.
no setterinherited
name String
A descriptive name for this step.
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited