Skip to content

Instantly share code, notes, and snippets.

@sawin0
Last active February 12, 2024 03:05
Show Gist options
  • Save sawin0/1f6524be429ac20fc94dc1b1f4771791 to your computer and use it in GitHub Desktop.
Save sawin0/1f6524be429ac20fc94dc1b1f4771791 to your computer and use it in GitHub Desktop.
Concurrent Asynchronous Operations in Dart: A Guide to Future.wait link: https://www.linkedin.com/pulse/concurrent-asynchronous-operations-dart-guide-sabin-ranabhat-u70nf
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() async {
print("Fetching todo data from JSONPlaceholder API using Future.wait method...");
// Create a list of asynchronous tasks to fetch todo data from different users
List<Future<Map<String, dynamic>>> apiCalls = [
fetchTodoData(1),
fetchTodoData(2),
fetchTodoData(3),
fetchTodoData(4),
fetchTodoData(5),
fetchTodoData(6),
fetchTodoData(7),
fetchTodoData(8),
fetchTodoData(9),
fetchTodoData(10),
];
// Measure the time taken for all API calls to complete using Future.wait
Stopwatch stopwatch = Stopwatch()..start();
try {
// Use Future.wait to wait for all API calls to complete
List<Map<String, dynamic>> results = await Future.wait(apiCalls);
// Log the results
for (int i = 0; i < results.length; i++) {
print("Todo data for user $i: ${jsonEncode(results[i])}");
}
// Stop the stopwatch
stopwatch.stop();
print("All API calls completed in ${stopwatch.elapsedMilliseconds} ms");
} catch (error) {
// Handle error: will be executed if any async function returns error
print("Error occurred: $error");
}
}
Future<Map<String, dynamic>> fetchTodoData(int todoId) async {
// Fetching todo data from the JSONPlaceholder API
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/$todoId'));
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('Failed to fetch todo data for user $todoId');
}
}
Future<void> cleanUpResources() async {
// Implement cleanup logic, e.g., closing files or DB, releasing connections, etc.
print("Performing cleanup of resources...");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment