run<T> method
Future<T>
run<T>(
- String? key,
- Future<
T> operation(), { - DeduplicationPolicy policy = DeduplicationPolicy.reuseInFlight,
Runs operation under key according to policy.
If key is null, operation always runs — deduplication is
opt-in per call.
Implementation
Future<T> run<T>(
String? key,
Future<T> Function() operation, {
DeduplicationPolicy policy = DeduplicationPolicy.reuseInFlight,
}) {
if (key == null) return operation();
final existing = _inFlight[key];
if (existing != null) {
switch (policy) {
case DeduplicationPolicy.reuseInFlight:
return existing.then((value) => value as T);
case DeduplicationPolicy.ignoreNew:
return Future.error(
StateError('A request with key "$key" is already in flight.'),
);
case DeduplicationPolicy.replacePrevious:
_inFlight.remove(key);
break;
}
}
final future = operation();
_inFlight[key] = future.then<Object?>((v) => v).whenComplete(() {
if (identical(_inFlight[key], _inFlight[key])) {
_inFlight.remove(key);
}
});
return future;
}