avatarConstantin Stan

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3354

Abstract

d to get some data that can/should be available only in the future because of computational/logic reasons.</p><h2 id="a7b7">Isolates</h2><p id="c3c5">Single threading on the multi-core CPU devices we have more and more around us seems a bit inefficient.</p><p id="342c">The traditional way the developers make use of all processing power of a device is by using shared-memory threads that run concurrently. This method is complicated and error-prone.</p><p id="6437">Dart uses Isolates to take advantage of all the available processing power. Isolates allow true parallel code execution and this results in improved performance and overall application responsiveness.</p><p id="7beb">All Dart programs start with at least one Isolate instance and that one is the <b>main</b> <b>Isolate</b>, where all of our application code runs.</p><p id="99a1">To have our code executed in parallel we must create new Isolate instances. These will run in parallel with the main Isolate. Isolates are completely independent, with their own memory heap, ensuring that no isolate’s state is accessible from any other isolate.</p><p id="42f1">For establishing communication between isolates (dispatch/receive data) we need to exchange messages. These can be primitive values, such as <code>null</code>, <code>num</code>, <code>bool</code>, <code>double</code>, or <code>String</code>, or simple objects such as a <code>List<Cat></code>. Passing more complex objects, such as a <code>Future</code> or <code>http.Response</code> between isolates might result in errors.</p><p id="0d1d"><b>Isolate.spawn</b> expects to be passed a static or top-level function.</p><div id="acba"><pre><span class="hljs-keyword">import</span> <span class="hljs-string">'dart:math'</span>; <span class="hljs-keyword">import</span> <span class="hljs-string">'dart:isolate'</span>;</pre></div><div id="f5cf"><pre><span class="hljs-keyword">class</span> <span class="hljs-symbol">Cat</span> { DateTime birthday;</pre></div><div id="df55"><pre> Cat.baby() { birthday <span class="hljs-operator">=</span> DateTime.now()<span class="hljs-comment">;</span> }</pre></div><div id="7820"><pre> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> meow(<span class="hljs-built_in">int</span> s) <span class="hljs-keyword">async</span> { <span class="hljs-keyword">await</span> Future.delayed(<span class="hljs-built_in">Duration</span>(seconds: s)); <span class="hljs-built_in">print</span>(<span class="hljs-string">'Meow!'</span>); } }</pre></div><div id="0be4"><pre><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">main</span>() <span class="hljs-keyword">async</span></span> { <span class="hljs-keyword">var</span> timeInterval = <span class="hljs-number">10</span>; <span class="hljs-keyword">var</span> random = Random.secure(); <span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> i=<span class="hljs-number">0</span>; i<<span class="hljs-number">100</span>; i++) { <span class="hljs-keyword">await</span> Isolate.spawn(Cat.meow, random.nextInt(timeInterval)); } <span class="hljs-keyword">await</span> Future.delayed(Duration(seconds: timeInterval+<span class="hljs-number">1</span>)); }</pre></div><p id="d13c">We modified the Cat class and transformed the <b>m

Options

eow</b> method into a static (class) method. We also changed it to accept <b>s</b>, a parameter that represents the number of seconds in which the cat has to meow. This method will be used to see the Isolate at work.</p><p id="d9a4">In the main Isolate, we declare a time interval of 10 seconds and a random generator. We then spawn 100 Cat.meow methods in the next 10 seconds, each running in a dedicated Isolate.</p><p id="c030">We also make sure that the <b>main Isolate</b> runs a bit longer than the other isolates it spawned, otherwise we’ll see only the output that was spawned with 0 seconds delay.</p><p id="fef9">When compiling to JavaScript, isolates get converted into <a href="https://www.w3schools.com/html/html5_webworkers.asp">web workers</a>.</p><p id="458e">Note that this won’t work in DartPad. You can test it in a Dart/Flutter project setup in your favorite editor (I use <a href="https://code.visualstudio.com">Visual Studio Code</a>, though there are other great options out there).</p><p id="cece"><a href="https://flutter.dev">Flutter</a> projects can use both platform-specific and cross-platform code. The latter is written in <a href="https://dart.dev">Dart</a>, and, for building Flutter apps, some basic knowledge of Dart is required.</p><p id="4da1"><a href="https://medium.com/tag/fluttering-dart/archive"><b>Fluttering Dart</b></a>’s goal is to explore fundamental knowledge and unveil tips & tricks of the powerful programming language that brings Flutter to life.</p><p id="ace2">In the previous parts of the series, we went through the Dart <a href="/@constanting/fluttering-dart-9a3e74b0d9c5"><b>built-in data types</b></a><b>, <a href="/@constanting/fluttering-dart-b37110f4d1bf">functions</a>, <a href="/@constanting/fluttering-dart-ee493f4b0440">operators</a>,</b> <a href="/@constanting/fluttering-dart-the-flow-7be2080763ad"><b>control flow statements</b></a><b> </b>and <a href="https://readmedium.com/fluttering-dart-oop-8b92cd89a7f0"><b>object-orientated programming</b></a><b> (classes, objects and more)</b>.</p><p id="a4a4">In this part, we’ve discovered how to overcome the single-thread downside of Dart.</p><p id="fd43">Some of the code examples from above can be tried out, and played with, using <a href="https://dartpad.dev"><b>DartPad</b></a>.</p><p id="600c">In the next part of the <a href="https://medium.com/tag/fluttering-dart/archive"><b>Fluttering Dart</b></a> series, we’ll delve into <a href="https://readmedium.com/fluttering-dart-libraries-and-packages-972edf864ff9">libraries and packages</a>, crucial for structuring, using, reusing and sharing our code.</p><div id="1149" class="link-block"> <a href="https://readmedium.com/fluttering-dart-libraries-and-packages-972edf864ff9"> <div> <div> <h2>Fluttering Dart: Libraries and Packages</h2> <div><h3>Libraries and packages are crucial for structuring, using, reusing and sharing components in the Flutter and Dart…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*S0zj6ABC4wGSUcHiObW6RQ.jpeg)"></div> </div> </div> </a> </div><p id="f25e">Tha(nk|t’)s all!</p></article></body>

Fluttering Dart

Fluttering Dart: Futures and Isolates

How to overcome the single-thread downside

Photo by Createria on Unsplash

Dart is single-threaded. That means that all of our application code runs in the same thread. Unfortunately, our code might block the single thread execution if it runs very time-consuming operations like HTTP requests.

Futures

Futures come in to resolve this by allowing us to perform asynchronous operations. For representing and working with the results of these operations we get the async and await keywords.

A Future<T> object provides a value, of type T, sometime in the future.

Let’s stick with our Cat class, that we used in the previous parts, and see an example from their realm:

import 'dart:math';
class Cat {
  DateTime birthday;
  Cat.baby() {
    birthday = DateTime.now();
  }
  Future<String> meow() async {
    var random = Random.secure();
    await Future.delayed(Duration(seconds: random.nextInt(10)));
    return 'Meow!';
  }
}
void main() async {
  Cat babyCat = Cat.baby();
  print('Baby cat says:');
  String babyCatMeow = await babyCat.meow();
  print('$babyCatMeow');
}

In the above example we create a baby cat. If you don’t know, cats do whatever they want, whenever they want. Meowing is no exception, and our kitten meows randomly in a 0–10 seconds interval.

The meow method of the Cat class is asynchronous. It returns a string in the future after it awaits for a random number of seconds (0–10). The Future.delayed method stops the single-thread execution for a given duration. Note that we also have to make our main asynchronous and await for the meow result.

This mechanism of an async method that awaits for a result applies whenever we need to get some data that can/should be available only in the future because of computational/logic reasons.

Isolates

Single threading on the multi-core CPU devices we have more and more around us seems a bit inefficient.

The traditional way the developers make use of all processing power of a device is by using shared-memory threads that run concurrently. This method is complicated and error-prone.

Dart uses Isolates to take advantage of all the available processing power. Isolates allow true parallel code execution and this results in improved performance and overall application responsiveness.

All Dart programs start with at least one Isolate instance and that one is the main Isolate, where all of our application code runs.

To have our code executed in parallel we must create new Isolate instances. These will run in parallel with the main Isolate. Isolates are completely independent, with their own memory heap, ensuring that no isolate’s state is accessible from any other isolate.

For establishing communication between isolates (dispatch/receive data) we need to exchange messages. These can be primitive values, such as null, num, bool, double, or String, or simple objects such as a List<Cat>. Passing more complex objects, such as a Future or http.Response between isolates might result in errors.

Isolate.spawn expects to be passed a static or top-level function.

import 'dart:math';
import 'dart:isolate';
class Cat {
  DateTime birthday;
  Cat.baby() {
    birthday = DateTime.now();
  }
  static void meow(int s) async {
    await Future.delayed(Duration(seconds: s));
    print('Meow!');
  }
}
void main() async {
  var timeInterval = 10;
  var random = Random.secure();
  for(var i=0; i<100; i++) {
    await Isolate.spawn(Cat.meow, random.nextInt(timeInterval));
  }
  await Future.delayed(Duration(seconds: timeInterval+1));
}

We modified the Cat class and transformed the meow method into a static (class) method. We also changed it to accept s, a parameter that represents the number of seconds in which the cat has to meow. This method will be used to see the Isolate at work.

In the main Isolate, we declare a time interval of 10 seconds and a random generator. We then spawn 100 Cat.meow methods in the next 10 seconds, each running in a dedicated Isolate.

We also make sure that the main Isolate runs a bit longer than the other isolates it spawned, otherwise we’ll see only the output that was spawned with 0 seconds delay.

When compiling to JavaScript, isolates get converted into web workers.

Note that this won’t work in DartPad. You can test it in a Dart/Flutter project setup in your favorite editor (I use Visual Studio Code, though there are other great options out there).

Flutter projects can use both platform-specific and cross-platform code. The latter is written in Dart, and, for building Flutter apps, some basic knowledge of Dart is required.

Fluttering Dart’s goal is to explore fundamental knowledge and unveil tips & tricks of the powerful programming language that brings Flutter to life.

In the previous parts of the series, we went through the Dart built-in data types, functions, operators, control flow statements and object-orientated programming (classes, objects and more).

In this part, we’ve discovered how to overcome the single-thread downside of Dart.

Some of the code examples from above can be tried out, and played with, using DartPad.

In the next part of the Fluttering Dart series, we’ll delve into libraries and packages, crucial for structuring, using, reusing and sharing our code.

Tha(nk|t’)s all!

Flutter
Dart
Programming
Optimization
Fluttering Dart
Recommended from ReadMedium