Last active
May 18, 2018 21:38
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| }); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The output of running this test...