Using Futures in Dart for Better Async Code

Dart bundles lots of functionality into its standard libraries, helping developers avoid reinventing the wheel from project to project. One of those wheels is a better way to handle asynchronous callback driven programs. Thanks to the Future class, potentially hard to follow callback code can be replaced with a more structured design.

(This is part 13 of an ongoing series about Dart.)

Intro

Let's pretend I have a set of potentially expensive methods that should be executed in order. Ideally, I should be able to write code like:

// Yikes! This will lock the page by running too

// many long processes in the main UI thread.

button.on.click.add((e) {

costlyQuery();

expensiveWork();

lengthyComputation();

print("done!");

});

Unfortunately, code like the above locks the main thread, freezing the application. Bummer.

Using callbacks is a typical way to make my UI responsive and move expensive processes off the initial handler. So I refactor the code into:

With all the nesting, though, things get a little confusing, and doesn't scale with a big algorithm. Imagine nesting these callbacks to 5 or 6 levels. Yikes.

Future is the future

The Future interface is designed to help design code that is more linear in appearance, without sacrificing the benefits of asynchronous behavior.

A Future represents a value that will be provided sometime in the future. The Future is a token that your method can return immediately, before the method performs its expensive calculations. Once the expensive work is done, the value can be given to the Future, thus notifying the consumer that the work is done.

Generally, the workflow when using a Future looks like:

Enter the method.

Construct a Future.

Return the Future (before the expensive work even starts).

At some point later, the event loop reaches the expensive work to be done.

Expensive work is finished, gives resulting value to Future.

The consumer of the Future is notified the value is present.

Refactoring to use a Future, the method signature becomes:

// return a Future immediately, then get to workFuture expensiveWork();

When using APIs that are not Future-based, it's often very helpful to also use a Completer. The Completer makes it easy to create and signal when a Future is complete. Only use a Completer when the asynchronous API that you're interacting with is not using Futures.

(Note that an upcoming addition to the language, method chaining, will make this code a bit nicer.)

Many futures

The Future class helps with handling multiple Future objects, if the order in which they are run doesn't matter. For example, you can kick off many Future instances and wait for all of them to finish with this code:

costlyQuery() {

return new Future.value("costly");

}

expensiveWork() {

return new Future.value("expensive");

}

lengthyComputation() {

return new Future.value("lengthy");

}

void main() {

Future.wait([

costlyQuery(),

expensiveWork(),

lengthyComputation()

]).then((values) => print(values));

// prints [costly, expensive, length]

}

Summary

Dart's Future interface represents a value that is provided sometime in the future. It can be returned immediately from a long running method, and it will signal the receiver when a value is ready.

Using a Completer to help manage a Future is a good idea. If you can run multiple Future objects in any order, consider using the Future.wait.

In which I port a snazzy little JavaScript audio web app to Dart, discover a bug, and high-five type annotations. Here's what I learned.

[As it says in the header of this blog, I'm a seasoned Dart developer. However, I certainly don't write Dart every day (I wish!). Don't interpret this post as "Hi, I'm new to Dart". Instead, interpret this post as "I'm applying what I've been documenting."]

This post analyzes two versions of the same app, both the original (JavaScript) version and the Dart version. The original version is a proxy for any small JavaScript app, there's nothing particularly special about the original version, which is why it made for a good example.

Three new language features just landed in the latest dev channel build of the Dart! Collectively known as null-aware operators, these new features will help you reduce the code required to work with potentially null objects.

I'm excited for these new abilities, because typing less is always a good thing. Read on to learn more, and be sure to try these new features on Dart Pad.

??
Use ?? when you want to evaluate and return an expression IFF another expression resolves to null.

exp ?? otherExp
is similar to

((x) => x == null ? otherExp : x)(exp)
??=
Use ??= when you want to assign a value to an object IFF that object is null. Otherwise, return the object.

obj ??= value
is similar to

((x) => x == null ? obj = value : x)(obj)
?.
Use ?. when you want to call a method/getter on an object IFF that object is not null (otherwise, return null).