📜 ⬆️ ⬇️

Asynchronous Programming in Dart (Part 1)

image

In this series of articles, I will not touch on the basics of programming on Dart itself, but on the issues of asynchrony in Dart.

Dart libraries are full of functions that return Future or Stream objects. These functions are asynchronous.
')
In the documentation we read:

Future - is like a promise to provide a result sometime in the future.
Stream is a way to get a sequence of values, such as, for example, a sequence of events (stream).

Future and Stream are included in the dart: async library, which can be used both in web application scripts and in scripts launched from the console.

Import the library as follows:

import 'dart:async'; 


Future


Dart libraries are full of functions returning Future. When the future is completed (some operation), its value is ready for use. And you can work with Future in different ways.

Use async and await


This is probably the easiest and most understandable way to handle future objects. It is very similar to synchronous.

 someFunction() async { var someVar = await functionXXL(); if (someVar == someParam) { //  -. } else { //  -. } } 

What is await: await expects the return of the result of an asynchronous function.

The async function (someFunction () - in our example) actually returns immediately before the asynchronous operations inside it are executed, but it returns Future, i.e. returns a “promise” to return certain values ​​later when the asynchronous processes are completed.

Inside the function with the async keyword, we can start one or more asynchronous processes. In other words, there can be a lot of await constructions (an example from the original documentation):

 runUsingAsyncAwait() async { //... var entrypoint = await findEntrypoint(); var exitCode = await runExecutable(entrypoint, args); await flushThenExit(exitCode); } 

It is important to note the following:

1. await works only inside the function body, which is preceded by the async keyword .
2. await constructions are executed in the same logical order as they are written. Those. until one await is executed, control is not transferred to the next.
3. async functions always return Future. If we do not want our function to return Future, we can use different solutions for this, for example, we can call the async function from another (non-async) function.

Now let's see how error handling happens in async functions:

 someFunc() async { // -  try { await someObject.start(); } catch (e) { //   } } 

We use the method Future - then ()


This option has an embodiment more similar to asynchronous. Consider an example (example from the original documentation):

 HttpRequest.getString(url).then((String result) { print(result); }).catchError((e) { //    . }); 

In this example, HttpRequest.getString (url) returns Future. When Future finishes, the then () method executes some code, in our case it outputs a string to the console. Note that error handling in this case occurs in the catchError construct.

The then (). CatchError () template is in itself an asynchronous version of try-catch.

The then () method returns Future, providing a convenient way to run multiple asynchronous functions in a specific order. If the callback function registered in then () returns Future, then () returns the equivalent Future. If callback returns a value of any other type, then () creates a new Future that terminates with that value.

Again an example from the original documentation:

 Future result = costlyQuery(); return result.then((value) => expensiveWork()) .then((value) => lengthyComputation()) .then((value) => print('done!')) .catchError((exception) => print('DOH!')); 

Here we see the “hook” of several .then ().

The functions in this example are processed in the following order:

1. costlyQuery ()
2. expensiveWork ()
3. lengthyComputation ()

Use the Future.wait () method


If we need to execute several asynchronous functions, and after completing their execution to execute some code, we can use the static method Future.wait (). Example:

 Future func1 = doSmth1(); Future func2 = doSmth2(); Future func3 = doSmth3();; Future.wait([func1, func2, func3]) .then((List values) { print('!'); }); 

Related Links


Asynchronous programming Dart (eng): ( link 1 , link 2 ).
You can also read: ( link 3 , link 4 )

I am not a guru in Dart, so I will be very grateful for your comments, clarifications and suggestions. Thanks for attention.

Source: https://habr.com/ru/post/256469/


All Articles