Easy State Sync Across JavaScript Sandboxes (Frames, Workers, Threads, Webviews)

by sourishkrouton 1/20/22, 6:42 PMwith 2 comments
by rektideon 1/20/22, 9:52 PM

It's not oriented specifically at state-sync'ing, but Comlink[1] comes to mind.

> Comlink.wrap(endpoint) and Comlink.expose(value, endpoint?) Comlink’s goal is to make exposed values from one thread available in the other. 'expose' exposes 'value' on endpoint, where endpoint is a postMessage-like interface. 'wrap' wraps the other end of the message channel and returns a proxy. The proxy will have all properties and functions of the exposed value, but access and invocations are inherently asynchronous. This means that a function that returns a number will now return a promise for a number.

Creating & exposing an EventEmitter in the main thread then proxy'ing it on each other thread ought create a reasonably similar experience to this Tangle library. The docs themselves discuss some of the extra difficulties if one is trying to proxy DOM Events[2], talking about this as a common usage pattern, but which is complicated by DOM Events not being cloneable.

For another example of Comlink in action, there's this blog post on using Redux across threads[3].

[1] https://www.npmjs.com/package/comlink

[2] https://github.com/GoogleChromeLabs/comlink#transfer-handler...

[3] https://dassur.ma/things/react-redux-comlink/