Skip to content

[Feature] JS: Add support for web workers as a asCoroutineDispatcher receiver #4688

Description

@bitspittle

What are you trying to do?

The coroutine libraries provide Window.asCoroutineDispatcher for the JS target.

On the web, you have a global window instance which works for main parts of your site, but window isn't available when you're inside a web worker script. Trying to access it in that context results in a runtime exception.

Since window is missing inside a web worker, I cannot currently easily create a coroutine in there without ugly workarounds (as far as I can tell).

(Initially, we used GlobalScope.launch as a workaround and suppressed the delicate API warning)

What problem does this actually solve?

Fixing this will allow users to use coroutines in web worker scripts exactly as they can in regular web scripts.

Your idea (optional)

It would be nice if the coroutines library supported WorkerGlobalScope.asCoroutineDispatcher

I made my own simple implementation (which you can find here). No promises on this not having some issue that I haven't realized yet.


P.S. There is also an interface in JS called WindowOrWorkerGlobalScope which would probably be an even better receiver to target, but I am not sure if you'd run into a reason where it will still be better to split their implementations.

I created my own workaround to support WindowOrWorkerGlobalScope (which you can find here), but if official coroutines ever changes the receiver for asCoroutineDispatcher I can remove it.

P.P.S. The coroutine library provides Window.awaitAnimationFrame which delegates to requestAnimationFrame under the hood. If you want to support that for workers as well, you would probably need to add an additional extension method for DedicatedWorkerGlobalScope (and not WorkerGlobalScope), which added support for requestAnimationFrame in 2023.

Prior art or similar ideas (optional)

No response

Anything else? (optional)

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions