Vivasoft-logo

অ্যাসিংক্রোনাস প্রোগ্রামিং উদাহরন

উপরে আমরা অ্যাসিঙ্ক্রোনাস প্রোগ্রামিং এবং ডার্টে কিভাবে এর ব্যাবহার হয় এটা দেখলাম। এখন আমরা একটি উদাহরন দেখব যাতে আমাদের ধারনা আরও সঠিক হয়। এখানে নেটওয়ার্ক অপারেশনের বিরতি বোঝানোর জন্যে Future.delayed নামে ডার্ট এর একটি ফাংশন ব্যাবহার করা হয়েছে। যেখানে আমরা কতক্ষণ বিরতি দিতে চাই সেটা Delayed অবজেক্টের প্যারামিটার ইউজ করে বলে দেয়া যায়। এখানে প্রিন্ট স্টেটমেন্ট ইউজ করা হয়েসে। আমরা ভাল ভাবে দেখে উদাহরনটি খাতায় এক্সিকিউশন ফ্লোটা লিখে দেখতে পারি এবং এখানে নিচে দেয়া আউটপুটের সাথে মিলিয়ে দেখতে পারি।

Future fetchUserData() async {
print("1. Start fetching user data...");

String userData = await simulateNetworkRequest();
print("2. User data fetched: $userData");

print("3. Fetching additional user details...");
simulateAdditionalRequest().then((value) {
  print("4. Additional user details fetched: $value");
});

print("5. End fetching user data.");
}

Future simulateNetworkRequest() async {
print("6. Simulating network request...");
await Future.delayed(Duration(seconds: 2)); // Simulate a network delay
return "User data";
}

Future simulateAdditionalRequest() async {
print("7. Simulating additional request...");
await Future.delayed(Duration(seconds: 1)); // Simulate a delay
return "Additional details";
}

void main() {
print("Main function starts.");

fetchUserData().then((_) {
  print("8. Async operation completed.");
});

print("Main function continues executing...");

// Let's add a delay to ensure the program doesn't exit immediately
Future.delayed(Duration(seconds: 4), () {
  print("9. Main function ends.");
});
}
 

আউটপুটঃ

Main function starts.

1. Start fetching user data...
6. Simulating network request...
Main function continues executing...
2. User data fetched: User data
3. Fetching additional user details...
7. Simulating additional request...
5. End fetching user data.
8. Async operation completed.
4. Additional user details fetched: Additional details
9. Main function ends.
 

অ্যাসিংক্রোনাস প্রোগ্রামিং অনেক সময় কনফিউজিং লাগতে পারে। চর্চা করতে করতে সহজ হয়ে যাবে। এটা খুবই শক্তিশালী এবং একই সাথে মজার একটি বিষয়।