Book Image

DART Cookbook

By : Ivo Balbaert
Book Image

DART Cookbook

By: Ivo Balbaert

Overview of this book

Table of Contents (18 chapters)
Dart Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using isolates in web apps


In this recipe, you will learn how to use isolates in a web application in the project using_web_isolates. This example runs in the Dart VM embedded in a browser as well as compiled to JavaScript. In the latter case, it uses HTML5 Web workers, which runs in the background independently of other scripts without affecting the performance of the page.

How to do it...

The main isolate in using_web_isolates.dart runs the following code:

import'dart:isolate';
import'dart:html';
import'dart:async';

main() {
  Element output = querySelector('output');
  SendPortsendPort;
  ReceivePortreceivePort = new ReceivePort();
  receivePort.listen((msg) {
    if (sendPort == null) {
    sendPort = msg;
  } else {
  output.text += 'Received from isolate: $msg\n';
  }
});

String workerUri = 'worker.dart';
int counter = 0;
// start 3 isolates:
for (int i = 1; i <= 3; i++) {
  Isolate.spawnUri(Uri.parse(workerUri), [], receivePort.sendPort).then((isolate) {
    print('isolate spawned...