Search code examples
dartweb-worker

Dart: in browser webworker written in dart and used in dart2js


Basically I am now very confused: the setup is very simple - I want to use dart to write the main app and the web worker part - a part that requires access to the same APIs the regular JS web worker has and that runs as a real worker when deployed (i.e. compiled to js).

As far as I understand dart isolates are not what I want because when compiled to JS those execute as part of the main thread even if they do not share state with the main code - this is not acceptable for my use case.

Also if I understand correctly I cannot use dart code if I am to use Worker API with a script uri, but even if I could it has to be a completely separate project and cannot be part of my main code (like it is with isolates).

Is my scenario possible at all with the current state of Dart? A simplified example on how to use web worker from dart and write the worker code in dart as well and having access to xmlhttprequest would be great. I am aware that I would probably not be able to transfer objects without serialization/deserialization but that is okay.

Thanks.


Solution

  • Isolates in dart2js will be mapped to workers. And you should be able to use either spawn or spawnUri. So that part should be fine.

    At the moment you're more likely to have problems developing in Dartium, where isolates don't map to workers. They run in parallel, but don't have access to worker APIs. That's being worked on. That's also the reason you can't use spawn in Dartium, to prevent spawning something with dart:html code that will break if it tries to use those APIs. It's unfortunate that even something as simple as print() will throw in a Dartium isolate right now. But as far as I know, it all works well in deployment.