Fork me on GitHub
#clojurescript
<
2022-04-02
>
DrLjótsson09:04:08

I'm experimenting with web workers in Clojurescript (through shadow-cljs). Is there a simple way to send cljs data structures back and forth from the web worker?

DrLjótsson09:04:47

I've tried cljs-bean but that doesn't preserve :valin {:key :val} (turned into "val")

DrLjótsson10:04:59

Got it working using com.cognitect/transit-cljs

saidone10:04:46

Excellent choice @brjann

DrLjótsson10:04:33

Next question: Is it possible to instruct a web worker to call a specific function? I've tried to send this map to the web worker {:fn 'my.ns.my-fn} .

DrLjótsson10:04:25

The web worker receives the map as m. I check (:fn m) and it returns my-ns.my-fn

DrLjótsson10:04:51

But nothing happens when I call ((:fn m))

DrLjótsson10:04:13

Do I need to resolve the symbol some way?

p-himik10:04:08

Instead of dynamically resolving arbitrary functions, if the set of functions that you'd want to call in a web worker is known then just create a registry of them.

DrLjótsson10:04:55

Yes, that was my first idea. But it felt nicer to send the symbol name. But i guess it won’t survive advanced compilation anyway?

p-himik10:04:36

You can still send the symbol name, and make that registry index functions by the symbols. :) If there are a lot of such functions, you can replace defn with your own macro that automatically populate the registry. > But i guess it won’t survive advanced compilation anyway? That's my guess but I haven't checked. I.e. the symbols themselves will definitely survive but resolve might not work - because the original namespace and function name were renamed.

DrLjótsson11:04:05

> You can still send the symbol name, and make that registry index functions by the symbols. :) If there are a lot of such functions, you can replace defn with your own macro that automatically populate the registry. Oh yeah, I didn't think of that. Great solution, thanks!

👍 1
saidone10:04:39

not 100% sure though

p-himik10:04:43

I'd use resolve. But not sure whether it would work in optimized JS. intern simply doesn't exist in CLJS.