Loading...
Loading...
Handle asynchronous operations safely using Futures and Streams.
npx skill4agent add dart-lang/skills dart-async-programmingFutureStreamFuture<T>asyncawaitFuture.waitStream<T>await forlisten()async*yieldStreamControllerasyncawait.then()try-catchFuture<String> fetchUserData(String userId) async {
try {
final result = await api.getUser(userId);
return result.name;
} catch (e, stackTrace) {
// Handle specific errors or rethrow
logError('Failed to fetch user: $e', stackTrace);
throw UserFetchException(e.toString());
}
}Future.waitFuture<UserProfile> loadCompleteProfile(String userId) async {
try {
final results = await Future.wait([
api.getUser(userId),
api.getUserPreferences(userId),
api.getUserHistory(userId),
]);
return UserProfile(
user: results[0] as User,
preferences: results[1] as Preferences,
history: results[2] as History,
);
} catch (e) {
throw ProfileLoadException('Failed to load profile components: $e');
}
}await forFuture<int> calculateTotal(Stream<int> numberStream) async {
int total = 0;
try {
await for (final number in numberStream) {
total += number;
}
} catch (e) {
logError('Stream processing failed: $e');
return -1;
}
return total;
}async*yieldStream<int> generateCountdown(int from) async* {
for (int i = from; i >= 0; i--) {
await Future.delayed(const Duration(seconds: 1));
yield i;
}
}StreamControllerclass DataManager {
final StreamController<DataEvent> _controller = StreamController<DataEvent>.broadcast();
Stream<DataEvent> get dataStream => _controller.stream;
void addData(DataEvent event) {
if (!_controller.isClosed) {
_controller.add(event);
}
}
void dispose() {
_controller.close();
}
}Stream<String> processNetworkStream(Stream<List<int>> byteStream) async* {
final safeStream = byteStream
.handleError((e) => logError('Network error: $e'))
.timeout(
const Duration(seconds: 5),
onTimeout: (sink) {
sink.addError(TimeoutException('Stream timed out'));
sink.close();
},
)
.transform(utf8.decoder)
.transform(const LineSplitter());
await for (final line in safeStream) {
if (line.isNotEmpty) yield line;
}
}StreamControllerStreamController.broadcast().then().catchError()asyncawaittry-catchawaitFuture.waitStreamControllerclose()close()asyncawait.then()try-catchFuture.waitawait forforEachlistenStreamControllerclose()await fordart-idiomatic-usagedart-concurrency-isolates