GoogleChromeLabs / comlink

Comlink makes WebWorkers enjoyable.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Push notifications from web worker

tgallagher2017 opened this issue · comments

Reading the documentation, I got the sense Comlink is a pull structure, such that if the main thread wanted something, it pulls it from the Web worker. The Web worker I currently have set up without using Comlink gathers highly compressed data from a REST endpoint, expands it and then sends the expanded data to the main thread through its post, which gets received by the onMessage() in the main thread.

I don't see such a mechanism in Comlink, unless I'm missing that part of the tutorial. If it's not part of Comlink, can this be added?

While most of the demos work by invoking a function on a worker and receiving a value, there's nothing preventing you inverting the logic and having the worker invoke a function on the main thread instead. It just depends on which side you setup the proxy.

To expand on that further if you want to go bidirectional, it's probably best to setup MessageChannels between the two and then use these for the proxy.

Thanks, I'll take a look at MessageChannels since I'm still experimenting. I'm hoping I can pull the data, post the "data converted" action, and have an RxStore listener on the other side to then trigger UI updates.

@tgallagher2017 By the way workers also support the BroadcastChannel API that is in all major browsers as of 2022. -- You can do "channels" which are just event buses that can be listened to or broadcast into, across tabs, iframes, workers, as long as it's the same origin.

(It's not comlink, sure, but maybe it serves your needs. 🤷‍♂️)

@tgallagher2017 It sounds like what you're looking for is a way to do pub-sub. Comlink does not have built-in mechanisms for pub-sub.

I am the author of a library called Transporter that was heavily influenced by Comlink but attempts to have more real word usability. With Transporter you can do pub-sub using Observables. Transporter also has an API called BroadcastSubject, in the browser package, that uses BroadcastChannel under the hood to provide an Observable interface on top of BroadcastChannel.