Skip to content

Instantly share code, notes, and snippets.

@jasonaguilon-wf
Last active May 18, 2018 21:38
Show Gist options
  • Select an option

  • Save jasonaguilon-wf/3cee8ced77dae37c801514a236cac25a to your computer and use it in GitHub Desktop.

Select an option

Save jasonaguilon-wf/3cee8ced77dae37c801514a236cac25a to your computer and use it in GitHub Desktop.
Example code that shows dart2js uses Web Worker to run a dart Isolate.
import 'dart:isolate' show Isolate, ReceivePort, SendPort;
import 'dart:js' as js show context, JsFunction, JsObject;
import 'package:test/test.dart';
js.JsObject currentWorker() {
js.JsFunction JsWorkerGlobalScope = js.context['WorkerGlobalScope'];
if (JsWorkerGlobalScope == null) return null;
js.JsObject self = js.context['self'];
if (!self.instanceof(JsWorkerGlobalScope)) return null;
return self;
}
void printCurrentWorker([SendPort replyTo]) {
if (currentWorker() == null) {
print('Web Worker not found. Must be in the browser UI thread.');
replyTo?.send(null);
return;
}
replyTo?.send('Web Worker found. In a thread different from the browser UI.');
}
void main() {
test('The browser UI thread is not a Web Worker', () {
printCurrentWorker();
expect(currentWorker(), isNull);
});
test('Spawning an Isolate puts code in a Web Worker', () async {
var response = new ReceivePort();
await Isolate.spawn(printCurrentWorker, response.sendPort);
String message = await response.first;
print(message);
expect(message, isNotNull);
});
}
@jasonaguilon-wf
Copy link
Author

jasonaguilon-wf commented May 18, 2018

The output of running this test...

$ pub run test -p chrome --pub-serve=59018 test/worker_test.dart
00:01 +0: compiling test/worker_test.dart
"pub serve" is compiling test/worker_test.dart...
00:07 +0: The browser UI thread is not a Web Worker
Web Worker not found. Must be in the browser UI thread.
00:07 +1: Spawning an Isolate puts code in a Web Worker
Web Worker found. In a thread different from the browser UI.
00:07 +2: All tests passed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment