Is there a sample showing how to use web workers ...
# javascript
m
Is there a sample showing how to use web workers in KotlinJS? I have no prior js experience so JS code is not very helpful for me.
j
Can't help since my JS background is weak but if KotlinJS is anything like KotlinJVM, you should probably invest into getting familiar with JS first. At least on understanding regular JS code, which you'll probably find a lot.
💯 1
âž• 1
d
For any JS api you can write or perhaps find kotlin bindings that use
external
modifier
Look up kotlin js interoperability
m
Essentially my problem boils down to the fact that Worker needs a separate .js file and I’m not sure it’s possible to do in Kotlin JS.
I found this trivial example https://github.com/mdn/simple-web-worker and main.js creates a Worker which needs a separate js file as a constructor param. In this example it’s worker.js file.
d
Ok, so you need to use a separate module as its target
m
I wish there was an easier way. I found out that you can inline it in JS by dynamically creating this separate file. https://stackoverflow.com/questions/5408406/web-workers-without-a-separate-javascript-file/6454685 I can almost do it with kotlin but I’m not sure how to transform:
Copy code
val worker_fn = { worker: Worker ->
        worker.postMessage("msg from worker")
    }
into
Copy code
function(e) { postMessage('msg from worker'); }
n
this looks like it should match, does it fail anywhere ?
the javascript version seems to expect a event.. so maybe
Copy code
{e: dynamic -> postMessage("msg from worker") }
you might also have to define
worker
via
external
keyword
m
yeah this matches! How dow I define external worker?
p
@mzgreen you should watch talk from kotlin conf by Erik Hellman, he was showing sample that uses web workers
m
I’ll definitely check it out, thank you! 🙂