UNPKG

575 BPlain TextView Raw
1import type { EventBasedChannel } from 'async-call-rpc'
2
3export class WorkerChannel implements EventBasedChannel {
4 /**
5 * @param worker Pass the Worker in the main thread.
6 */
7 constructor(public worker: Worker = self as any) {}
8 on(listener: (data: unknown) => void): void | (() => void) {
9 const f = (ev: MessageEvent): void => listener(ev.data)
10 this.worker.addEventListener('message', f)
11 return () => this.worker.removeEventListener('message', f)
12 }
13 send(data: unknown): void {
14 this.worker.postMessage(data)
15 }
16}