Implementing a WebWorker in Kotlin


#1

The JavaScript worker API is exposed to Kotlin and I can easily create web workers with it. Can I also write the worker’s code in Kotlin?


#2

Yes, you can. Why not?


#3

Thank you for your response! After some more thinking I think my problems are the following:

  1. I don’t know how to put my code into the right context. How can I tell the compiler that self has a method addEventListener and a method postMessage?
  2. Would my project then have two main functions, one for the main web page and one for the worker thread? If so, how can I configure IntelliJ to compile the two main functions into two separate output files?

As I’m typing this, I think that I could probably solve problem 1 with inline JavaScript that just expects these variables to be set. :thinking:


#4

I don’t know how to put my code into the right context. How can I tell the compiler that self has a method addEventListener and a method postMessage?

external val self: ServiceWorkerGlobalScope

Would my project then have two main functions, one for the main web page and one for the worker thread? If so, how can I configure IntelliJ to compile the two main functions into two separate output files?

There are number of ways. First, you don’t necessarily need main function, the following trick also works fine:

private val dummy = start()

fun start() {
    // do something
}

Second, you don’t need main function in non-worker script at all. You can define a function and call it, say, from another <script> tag or from <body onload="...">.

Third, you can put worker in a separate module.