I have a pretty strange task. I am trying to do hi...
# javascript
b
I have a pretty strange task. I am trying to do high performance communication between a web worker and the main js thread in a browser. Browsers use structured clone algorithm to pass javascripts objects between web workers and main threads, which is orders of magnitude faster than serialization. I am trying to make use of it without losing types. Here's code that is ran from the web worker:
Copy code
private external var postMessage: dynamic

data class MessageToMain(
    val text: String
)

fun testInWorker() {
    val message = MessageToMain("Hello world!")
    postMessage(message)
}
And here's code that is ran in the main js thread:
Copy code
worker.onmessage = {
    val data = it.data
    console.log(data)
    val typed = data as MessageToMain
    println(typed)
    Unit
}
console.log outputs
{text: "Hello world!"}
, but trying to cast it to MessageToMain unsurprisingly results in
ClassCastException
being thrown. Considering that the actual javascript object in
data
should satisfy the class definition of MessageToMain, I am wondering if there is a way to forcefully cast it.
p
the js object in data most likely does not satisfy the definition of MessageToMain anymore, I suspect equals/hashcode/copy/component1 functions are be missing. If that’s the case it may be better to use an
external interface
for the messages
b
That's a good point. I havent considered that the methods are stripped from the object. I will give the external interface approach a try, but unfortunately I think that means I would need to have a duplicate declaration, one for classes and one for external interfaces. Thanks for the advice.
t
You can deserialize incoming data if you need data class functionality
b
A serialization library like kotlinx.serialization would be the simple approach and usually the best approach, but in this case im trying to achieve higher performance than what is possible with those approaches.