Friday, March 9, 2012

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 interface, 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 keep expensive processes off the main thread. So I refactor the code into:

 button.on.click.add((e) {
   costlyQuery(() {
     expensiveWork(() {
       lengthyComputation(() {
         print("done!");
       });
     });
   });
 });

The method signatures now look like:

void costlyQuery(onComplete());
void expensiveWork(onComplete());
void lengthyComputation(onComplete());

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:

  1. Enter the method.
  2. Construct a Future.
  3. Start the expensive work in some callback or isolate.
  4. Return the Future (before the expensive work is finished).
  5. ... expensive work continues ...
  6. Expensive work is finished, gives resulting value to Future.
  7. 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 work
Future expensiveWork();

When using Futures, it's often very helpful to also use a Completer. The Completer makes it easy to create and signal when a Future is complete. The implementation of expensiveWork() would look like:

Future<Results> costlyQuery() {
  var completer = new Completer();

  database.query("SELECT * FROM giant_table", (results) {
    // when complete
    completer.complete(results);
  });

  // this returns essentially immediately,
  // before query is finished
  return completer.future; 
}

A client who calls costlyQuery() will immediately receive a Future in response. The client is notified when a value exists when the then() method is called on futureResults.

Future<Results> futureResults = costlyQuery();
futureResults.then((results) => renderTable(results));

Or, if you want to streamline the code:

costlyQuery().then((results) => renderTable(results));

I really like how the code reads. "Run a costly query, then, render the table."

Chaining futures

The real power of Futures comes in when you need to run multiple async methods in order, as our initial example illustrates.

Luckily, the Future interface provides a chain() method to make this easy. Assuming each of our expensive methods returns a Future, behold the glory:


 button.on.click.add((e) {
   costlyQuery()
   .chain((value) => expensiveWork())
   .chain((value) => lengthyComputation())
   .then((value) => print("done!"));
 });

Error handling

Futures pass along both values and exceptions. Here's the code for handling an exception and giving it to a Future.

  database.query("SELECT * FROM giant_table", (results) {
    // when complete
    completer.complete(results);
  }, (error) {
    completer.completeException(error);
  });

You can use any object to represent an exception, which is why we are simply passing the error to the Future as an exception.

Here's how to handle any exception from any of the chain() methods:

 button.on.click.add((e) {
   Future result = costlyQuery();
   result.handleException((exception) => print("DOH!"));

   result.chain((value) => expensiveWork())
         .chain((value) => lengthyComputation())
         .then((value) => print("done!"));
   
 });

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

Parallel futures

The Futures interface 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.immediate("costly");
}

expensiveWork() {
  return new Future.immediate("expensive");
}

lengthyComputation() {
  return new Future.immediate("lengthy");
}

void main() {
  Futures.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 Futures interface.

Next Steps

Read the previous Part 12 on Classes in DartRead more of my Dart poststry Dart in your browserbrowse the API docs, or file an issue request. Dart is getting ready, please send us your feedback!
Post a Comment

Disclaimer

I'm probably required to say that the views expressed in this blog are my own, and do not necessarily reflect those of my employer. Also, except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the BSD License.