withContext<T> method

Future<T> withContext<T>(
  1. String transactionId,
  2. Map<String, dynamic> attributes,
  3. Future<T> operation()
)

Run code with a specific transaction context

Implementation

Future<T> withContext<T>(
  String transactionId,
  Map<String, dynamic> attributes,
  Future<T> Function() operation,
) async {
  final generation = _generation;
  final state = _TransactionState(generation)..stack.addAll(_contextStack);

  return await runZoned(() async {
    final context = TransactionContext(
      transactionId: transactionId,
      attributes: attributes,
      parent: currentContext,
    );

    pushContext(context);
    try {
      return await operation();
    } finally {
      // A reset invalidates this frame; it must not pop a new context that
      // the caller deliberately established after shutdown in the same zone.
      if (_generation == generation) popContext();
    }
  }, zoneValues: {_zoneStateKey: state});
}