Cancellation and timeouts
suggest changeIn Dart, asynchronous tasks are represented by Future and Stream. Because standard Dart Futures cannot be forcefully aborted from the outside once scheduled, cancellation requires either setting a timeout or using cooperative cancellation tokens.
Timeouts on Futures with Future.timeout
The Future.timeout() method enforces a maximum duration on any future. If the operation does not complete within the specified Duration, a TimeoutException is thrown:
import 'dart:async';
Future<String> fetchUserData() async {
// Simulates a slow backend call
await Future.delayed(Duration(seconds: 5));
return 'User: Alice';
}
Future<void> main() async {
try {
String data = await fetchUserData().timeout(Duration(seconds: 2));
print(data);
} on TimeoutException catch (e) {
print('Operation timed out: ${e.message}');
}
}
Providing a Fallback on Timeout
Instead of catching a TimeoutException, supply an onTimeout callback to return a default fallback value:
Future<void> main() async {
String data = await fetchUserData().timeout(
Duration(seconds: 2),
onTimeout: () => 'Cached Default User',
);
print('Result: $data'); // Cached Default User
}
Timeouts on Streams
Dart Streams also provide a .timeout() operator that monitors the duration between emitted events:
import 'dart:async';
void main() async {
final controller = StreamController<int>();
final timedStream = controller.stream.timeout(
Duration(seconds: 1),
onTimeout: (sink) {
sink.addError(TimeoutException('No data received for 1 second'));
},
);
timedStream.listen(
(event) => print('Received: $event'),
onError: (err) => print('Stream error: $err'),
);
controller.add(1);
// Waiting longer than 1 second triggers onTimeout
}
Cooperative Cancellation with package:async
The official package:async provides CancelableOperation, which wraps a Future and allows callers to discard its result and notify handlers upon cancellation.
Add to pubspec.yaml:
dependencies:
async: ^2.11.0
Using CancelableOperation
import 'package:async/async.dart';
CancelableOperation<String> loadResource() {
return CancelableOperation.fromFuture(
Future.delayed(Duration(seconds: 3), () => 'Heavy Report Data'),
onCancel: () {
print('Underlying cleanup logic executed upon cancellation');
},
);
}
void main() async {
final operation = loadResource();
// Cancel before completion
await Future.delayed(Duration(seconds: 1));
await operation.cancel();
if (operation.isCanceled) {
print('Operation was canceled successfully');
}
// Attempting to await after cancel returns null or triggers onCancel
final result = await operation.valueOrCancellation('Fallback');
print('Final result: $result'); // Fallback
}
Canceling Stream Subscriptions
When consuming events from a Stream, store the returned StreamSubscription and call .cancel() to stop listening and release resources:
import 'dart:async';
void main() {
final timerStream = Stream.periodic(Duration(milliseconds: 500), (i) => i);
late StreamSubscription<int> subscription;
subscription = timerStream.listen((count) {
print('Tick: $count');
if (count >= 3) {
print('Canceling stream subscription');
subscription.cancel();
}
});
}
Aborting HTTP Requests
With package:http, call client.close() on an instantiated http.Client to abort active in-flight network connections:
import 'package:http/http.dart' as http;
Future<void> fetchWithAbort() async {
final client = http.Client();
// Schedule cancellation after 2 seconds
Future.delayed(Duration(seconds: 2), () => client.close());
try {
final response = await client.get(Uri.parse('https://httpbin.org/delay/5'));
print('Response: ${response.statusCode}');
} on http.ClientException catch (e) {
print('Request was canceled by closing the client: $e');
} finally {
client.close();
}
}