Hey everyone. Asynchronous Programming is notoriously hard to get in the first go. So, I tried to simplify the topic in my own way. Let me know in the comments whether it was helpful or not.
There are lines of code that take small amount of time to execute. For example:
print('something');
This line simply prints the text into the console and takes fractions of a second to complete.
Then there are lines of code that can take much more time to execute. For example, if we are fetching image from the internet. The larger the data we are trying to get, the more time it will take to load. Now, imagine if the internet is slow, or the server is down. It may take a lot of time to load, and during all this time, you have to wait.
Consider this:
void aFunction() {
print('step 1'); //first step
syncLoad('image from internet'); //function that is fetching image from the internet
print('step 3'); //third step
}
The first step executes within a fraction of second. Now, the second step. This function is responsible for fetching image from the internet, which may take a lot of time to complete. That means, the program will freeze for the time-being, and we have to wait for the time it will take to complete.
Let's take a real life example:
Suppose, you need the passport number of your friend.
Scenario-1: if you choose to call that person, various types of events can happen. That person may not pick up the call, or he/she may have forgotten it. In all these cases, you have to wait for them to give you the number. At this point you cannot move on to other tasks that you have.
Scenario-2: if you choose to email/text that person. Then you can move on to other tasks, and not just wait for the response.
Let's look into some code:
void main() {
stepOne();
stepTwo();
stepThree();
}
void stepOne() {
print('step 1');
}
void stepTwo() {
print('step 2');
}
void stepThree() {
print('step 3');
}
output:
step 1
step 2
step 3
Everything happens one after the another in order. This is Synchronous Programming. While it is a predictable way of coding, it has its downsides.
Consider this:
import 'dart:io';
void main() {
stepOne();
stepTwo();
stepThree();
}
void stepOne() {
print('step 1');
}
void stepTwo() {
Duration threeSeconds = Duration(seconds: 3); //we are creating a Duration object of 3 seconds.
sleep(threeSeconds); //this is a Synchronous operation. This will stop the program for 3 seconds before moving onto the next step.
print('step 2');
}
void stepThree() {
print('step 3');
}
output:
step 1
.....here the program will freeze for 3 seconds
step 2
step 3
So, you can imagine, what will happen if we write Synchronous code for time-taking tasks. The program will stop for the time-being and the next consecutive tasks will not be performed. This is the reason why we choose Asynchronous Programming for time-consuming tasks like fetching data from the internet or using database. We allow the time-taking tasks to run in the background and move onto the next consecutive tasks, and when the long task gets completed, we deal with the results.
Consider this:
void main() {
stepOne();
stepTwo();
stepThree();
}
void stepOne() {
print('step 1');
}
void stepTwo() {
Duration threeSeconds = Duration(seconds: 3);
Future.delayed(threeSeconds, (){
print('step 2');
});
}
void stepThree() {
print('step 3');
}
output:
step 1
step 3
//...after 3 seconds
step 2
The step 3 will be printed before, and the program will wait for 3 seconds and then step 2 will be printed. This is because, Future.delayed() is an Asynchronous operation(we will discuss about Futures in the next blog post). Future.delayed() is a function that takes Duration object(the time for which the operation will be delayed) and a callback(something that will be done after the delaying time).
Let's understand step-by-step:
first stepOne() is called. 'step 1' is printed in console.
second, stepTwo() is called. Duration object is initialized. Future.delayed() is called. As soon as Future.delayed() is called, since it is an Asynchronous method and has a delaying time of 3 seconds, it will run in the background. The program will move onto the next step, i.e. it will call stepThree().
Hence 'step 3' is printed and then after 3 seconds 'step 2' is printed.
By Asynchronous Programming, the code is not getting freezed and it moves onto the next consecutive steps and the long tasks are run in the background.
Key takeaways:
Synchronous Programming:
It's predictable.
Everything happens step by step. If one operation gets executed then and only then the next operation will be executed.
Not recommended for operations that take unpredictable amount of time.
Asynchronous Programming:
Tasks that take long time to execute are run in the background.
Meanwhile, other short tasks will be executed. When the long task gets executed, then we deal with the result.
Recommended for operations that take unpredictable amount of time.
That's it. I hope it was worthy of your time and helped you in some way. In the next post, we will be discussing about Futures and Async/Await. Can you please share it with the community? Would appreciate it. Please provide your feedback in the comments. Thanks for reading. Follow me on twitter @imtanaybanerjee