Last active
February 12, 2024 03:05
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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