Chapter 8. Working with Futures, Tasks, and Isolates

In this chapter, we will cover the following recipes:

  • Writing a game loop
  • Error handling with Futures
  • Scheduling tasks using Futures
  • Running a recurring function
  • Using isolates in the Dart VM
  • Using isolates in web apps
  • Using multiple cores with isolates
  • Using the Worker Task framework

Introduction

The Future class from dart:async lies in the basis of all asynchronous programming in Dart. A Future is, in fact, a computation that is deferred; it represents an object whose value will be available sometime in the future. It is not available immediately, because the function that returns its value depends on some kind of input/output and is, thus, unpredictable by nature. Here are some examples: a time-consuming computation, reading in a big dataset, and searching through a number of websites.

In the two previous chapters, quite a lot of recipes used Futures; in Chapter 6, Working with Files and Streams, we had the following recipes using Futures:

  • Reading and processing a file line by line
  • Concatenating files the asynchronous way
  • Downloading a file

In the preceding chapter, we used Futures in the following recipes:

  • Making a web server
  • Receiving data on the web server
  • Using sockets

In this chapter, we will concentrate on how to write elegant code for Futures and combine their possibilities with the execution of tasks and isolates to enhance the performance of our apps.

Dart runs single-threaded, so it uses, by default, only one CPU on a multi-core machine; if you want concurrency, you must use isolates. In the second part of the chapter, you will find recipes featuring isolates, Dart's mechanism to provide concurrency and parallelism in applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset