To understand the dart async, you must understand the type of execution flow.
There are 2 types in which the task or program can be executed.
- Synchronous Execution
- Asynchronous Execution(Async)
What is Synchronous Execution?
In general, every program you write works in a synchronous fashion.
Synchronous execution means the execution of program will work evaluating the values statement by statement(code instruction).
Synchronous Execution means the execution of program doesn’t move to the next expression until the current expression, function or block of code gets evaluated(executed).
Synchronous operation gets executed always on the main thread(A thread is a unit of program execution to evaluate or execute the block of code or program).
Each program has at least one thread to process its task or say program which is main thread.
For ex :
void main(){
tuition();
getDataFromServer();
print(“End”);
}
void tuition(){
print(“Dart Classes Ongoing”);
}
getDataFromServer(){
//Heavy Calculation which takes around 5 seconds to execute
}
In above example, execution starts with tuition function(i.e., executes each statements or code written in the tuition). After that it evaluates the getDataFromServer() function which takes around 5 seconds to execute. Till then the Main thread gets blocked as our execution flow can’t move further to the next instruction print(“End”) until current statement or function gets evaluated completely.
This Execution will not be useful when you want to make UI changes to your application or you want to continue your execution to next statement when current statement requires heavy calculation in the program. So, to overcome this situation the concept of asynchronous execution was introduced.
What is Asynchronous Execution ?
In general, your UI runs on a single thread to interact with user which is known as main thread. Therefore all code will run on main thread which might result in poor performance due to heavy calculations or consuming operations. Till the execution of those heavy operations your UI(i.e., main thread) is blocked. So, to run those heavy operations without blocking main thread or UI asynchronous execution comes to the rescue.
Let’s understand dart async with one of the useful concept known as then keyword.
What is then ?
As the name suggests, then keyword is used to wait for the asynchronous operation to complete written in particular function. After that then block gets executed which have the Future return type retrieved from that particular function.
Let’s take an example to briefly understand async operation using then keyword.
import 'dart:io';
void main() {
// then keyword is used to perform the calculation after particular async function gets executed completely. It must have a Future return type while using with then keyword for an async function. Here, readNews() returns the Future return type String to then block.
readNews().then((String news){
print(news);
});
}
// readNews() is an async function having return type of String which will be evaluated after some time in future.
Future<String> readNews() async{
print("War Started Today !!");
sleep(const Duration(seconds:5));
return "War Ended !!";
}
Output :
War Started Today !!
War Ended !!
In above example, first async function readNews() gets called. After the function completion then block associated with readNews() gets called which requires the return type passed by readNews function(here, String data type).
So, we can use then keyword with async function for asynchronous operations. Await is another alternative for then block to perform smoother asynchronous operations.
What is await ?
In dart async, await is used to wait for the execution of the function completes. await keyword is prefixed before the async function call. Await keyword can only be used in async functions as well as it’s always prefixed before the async functions to wait till that async function gets executed.
So to perform async function we need to declare main function as async function. To define any function as async we need to postfix the async keyword after the function-brackets().
Let’s take an example to briefly understand async operation using await keyword.
import 'dart:io';
games() async {
// sleep method is useful to sleep your thread for specific time duration mentioned.
sleep(const Duration(seconds:5));
return "Playing PUBG";
}
main() async {
print("Playing Clash Of Clans");
//await is prefixed before the async function games
var test= await games();
print(test);
}
Output :
Playing Clash Of Clans
Playing PUBG
In above example, program execution waits till the games() method gets executed and after that print statement is evaluated.
so, here async operation is used as the program execution will not move forward till the async function games() doesn’t get evaluated as we have used await function. Which will wait for the current function to get executed first and then move for further execution.
this process doen’t blocking main thread to execute any operation. But, we are just waiting for the games() function to be executed which is executing on the another thread.
Let’s take another async example scenario.
Future<void> getGameDetails() async {
var newsDigest = await gameReports();
print(newsDigest);
}
main() {
getGameDetails();
playingChess();
playingCricket();
playingCOC();
}
playingChess() {
print("Playing Chess now-a-days");
}
playingCricket() {
print("Playing Cricket now-a-days");
}
playingCOC() {
print("Playing Clash of clans now-a-days");
}
const game = 'Playing PUBG now-a-days';
const duration = Duration(seconds: 5);
// here Future<String> means the Return type of the function is String but function will be completed in future.
Future<String> gameReports() =>Future.delayed(duration, () => game);
Output :
Playing Chess now-a-days
Playing Cricket now-a-days
Playing Clash of clans now-a-days
Playing PUBG now-a-days
In above example, first we have called async function getGameDetails(). As it is an async task it will be executing on the separate thread. After that we have called three functions playingChess(), playingCricket() and playingCOC(). They all gets executed synchronously as they are executing on main thread. The output of the aync function getGameDetails() is printed at last because that asyc method takes around 5 seconds to execute. Before that all methods gets executed so their outputs or evaluations are printed before it.
Future API represents the result of the async functions which will be processed or completed later.
When a function returns the data type with future , two things happen
- the function will be queued up for the execution and returns an uncompleted Future object.
- when the execution is finished, the future object returns with value or an error.
In above example, gameReports() method which is more complex as well as slow is queud up for the execution first and then at the end of the execution it returns the future object with string type value.
So, in this way we can perform heavy calculations without blocking main thread or UI of the program and provide smoother experience to user.
Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.
Very good content and explanation, i really impress