Exploring Dart's Async Library

Use Dart's async library to keep work off the main UI thread and help your users have a smooth and performant experience. The dart:async library contains classes for timers, futures, streams, and more. Effective use of dart:async keeps your apps easier to understand and your UI snappy.

Telling the future is easier when you have all the data.

The event loop

Or, why this all matters.

Dart programs, just like JavaScript, have no shared-state threads. The UI and the program use the same thread of execution, so when the UI is updating the program isn't running. Conversely, when the programming is running, the UI isn't updating. Keeping work off of the main thread means more time for the UI to respond to user input, which means the UI feels snappy and responsive.

The runtime maintains an event loop and a queue of work to perform. The event loops pops work items off of the queue, one after another. While one work item is handled, the other work items sit in the queue patiently.

Examples of work items can include callbacks for mouse move, mouse click, scroll events, database fetches, window resizes, and programatic callbacks. That is, all of the events and callbacks registered by your program or generated by the browser end up in the queue to be processed by the event loop. It's clear that keeping the individual work items small is key to a performant application and UI.

(Note, in Dart you can create new isolates if you want concurrent program execution. In JavaScript, you can create new Web Workers to achieve the same effect.)

Async programming

As an analogy, consider these two scenarios:

1) Send an email, stop doing any work at all until you hear a response.
2) Send an email, continue on your day and handle the response when you get it.

The above code runs as you would expect, line by line. The file contents can be used immediately in the line after readAsStringSync().

However, if the file is large, the entire program is blocked waiting for the file to be read into memory. For simple command-line scripts this is usually acceptable, but for client-side apps or for server programs, blocking is totally not cool. Surely, we can do better!

To write responsive and asynchronous programs, you should not block on work but instead ask to be notified when the work is complete. Here is an example of an asynchronous API:

To summarize, asynchronous programming is the art of not blocking the main thread. Writing an asynchronous program can be tricky, because the program doesn't execute in what seems to be linear order. Strong abstractions and object models can help put an object-oriented interface on top of hard-to-follow asynchronous code.

The dart:async library

To help manage asynchronous programs, Dart bundles the dart:async library. Inside, you will find:

Future, for handling values returned later

Completer, to help create and finish Futures

Timer, for repeating tasks, and tasks scheduled for later

Stream, for streams of events

StreamController, to help create and manage a stream

Let's take a look at each of these classes.

Future and Completer, aka Producing values from the future

If an asynchronous method or function returns a single value (e.g. readAsString() returns one thing, the file contents), it should return a Future. A Future represents a value not yet available, with the expectation that the value will be available in the future. If a function needs to perform some work before generating a value, the function should return a Future instead of taking a callback parameter.

A Completer can help manage the creation, and completion, of a future value. It is recommended to use a Completer, instead of trying to work with a raw Future.

Here is an example method that uses a Completer to return and complete a Future.

The database.query() method takes a SQL query and a callback function to handle any results. Thanks to lexical scope, the callback has access to the completer, so it can complete the future with the expected value.

The second callback is run when the database driver encounters an error. Notice how you can complete a Future with an error. If you create a future, be sure to complete it with either a value or an error.

The getAccount() method immediately returns the completer's future, before it queries the database. Sometime in the future, after all the network I/O and database protocol handling, the results are generated and the the completer completes.

When a completer completes, the future generated by the completer gets a value, and code waiting for a value is notified.

Notice how catchError() is chained off of then(). This works because then() actually returns a Future.

Creating futures with values that exist now

Sometimes, you need to conform a synchronous API to an asynchronous API. That is, you might have a value available right now, however you need to wrap it in a Future. Luckily, there's a constructor for that.

Use new Future.immediate(value) to create a future whose value is available on the next event-loop iteration. Here is an example:

Future<bool> isOnline() {
return new Future.immediate(true);
}

It's rare that you have the value immediately available, especially when the API was originally designed to be asynchronous. Another use for immediate is to push the work that would be done on a value to the next event-loop cycle.

Similar to Future.immediate() is Future.of(), which runs a function, collects the result, and makes it available on the next event-loop iteration. Here is an example:

The function is run now, but the value isn't made available until the next event-loop iteration.

If you have a value available now, but you want to delay the completion of a Future, you can use Future.delayed(). The value is generated now, but the future waits before completing. Here is an example:

Popular posts from this blog

Now, this has to have a built-in somewhere in Scala , because it just seems too common. So, how to convert an Array to a List in Scala? Why do I need this? I needed to drop to Java for some functionality, which in this case returns an Array. I wanted to get that Array into a List to practice my functional programming skillz. **Update**: I figured out how to convert Arrays to Lists the Scala way. Turns out it's a piece of cake. val myList = List.fromArray(Array("one", "two", "three")) or val myList = Array("one","two","three").elements.toList The call to elements returns an Iterator , and from there you can convert to a List via toList . Nice. Because my first version wasn't actually tail recursive, what follows is a true tail recursive solution, if I were to implement this by hand. The above, built in mechanism is much better, though. object ArrayUtil { def toList[a](array: Array[a]): List[a] = { d

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. This post discusses the differences between the two implementations: file organization, dependencies and modules, shims, classes, type annotations, event handling, calling multiple methods, asynchronous programming, animation, and interop with JavaScript libraries. F

In which the virtues of automated mechanical arboreal pruning are extolled over quaint manual labor, as applied to web development build processes. The setup Ever notice how the primary bit of marketing for many traditional web programming libraries is their download size? Why is that? Check this out: Why does size matter so much for these libraries? Your first instinct is probably, "because the more bytes you shuttle across the wire, the slower the app starts up." Yes, this is true. I'd also say you're wrong. The primary reason that size matters for these libraries is because traditional web development has no intelligent or automated way to prune unused code so you can ship only the code that is used over the wire. The web is full of links, yet web dev has no linker The web development workflow is missing a linking step. A linker's job is to combine distinct project files into a single executable. A smart linker will only incl