Skip to content

Commit

Permalink
feat(webworker): support onConnect for webworker
Browse files Browse the repository at this point in the history
  • Loading branch information
unadlib committed Sep 8, 2024
1 parent 8864e42 commit 5cb27f4
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 6 deletions.
17 changes: 12 additions & 5 deletions examples/webworker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { Worker, Main } from './interface';

class MainTransport
extends WorkerTransport.Main<{ emit: Main }>
implements Worker {
implements Worker
{
async help() {
const response = await this.emit('help', { text: 'SOS!!!' });
return response;
Expand All @@ -21,13 +22,19 @@ class MainTransport

const worker = new Worker('worker.bundle.js');

(window as any).mainTransport = new MainTransport({
worker,
});

document.getElementById('btn')?.addEventListener('click', async () => {
const response = await (window as any).mainTransport.help();
const div = document.createElement('div');
div.innerText = `${new Date()}: ${JSON.stringify(response)}`;
document.body.appendChild(div);
});

// mock async init worker
setTimeout(() => {
(window as any).mainTransport = new MainTransport({
worker,
});
(window as any).mainTransport.onConnect(() => {
console.log('connected');
});
}, 1000);
9 changes: 8 additions & 1 deletion examples/webworker/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,11 @@ class WebWorkerTransport
}
}

(self as any).webWorkerTransport = new WebWorkerTransport();
// mock async init worker
setTimeout(() => {
(self as any).webWorkerTransport = new WebWorkerTransport();

(self as any).webWorkerTransport.onConnect(() => {
console.log('connected');
});
}, 2000);
74 changes: 74 additions & 0 deletions src/transports/workerTransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import { Transport } from '../transport';
// workaround: `tsc --skipLibCheck`.
declare var self: WorkerGlobalScope;

type ClientCallback = () => void | Promise<void>;

const connectEventName = 'worker-connect';

export interface WorkerMainTransportOptions
extends Partial<TransportOptions<TransferableWorker>> {
/**
Expand Down Expand Up @@ -50,6 +54,41 @@ export abstract class WorkerMainTransport<
listener,
sender,
});

this.emit({
// @ts-ignore
name: connectEventName,
respond: true,
silent: true,
}).then(this._handleConnectCallbacks);

// @ts-ignore
this.listen(connectEventName, this._handleConnectCallbacks);
}

private _connected = false;

private _handleConnectCallbacks = async () => {
if (this._connected) {
return;
}
this._connected = true;
this._onConnectCallback.forEach((callback) => {
callback();
});
this._onConnectCallback.clear();
};

private _onConnectCallback = new Set<ClientCallback>();

onConnect(callback: ClientCallback) {
if (this._connected) {
return callback();
}
this._onConnectCallback.add(callback);
return () => {
this._onConnectCallback.delete(callback);
};
}
}

Expand Down Expand Up @@ -79,6 +118,41 @@ export abstract class WorkerInternalTransport<
listener,
sender,
});

this.emit({
// @ts-ignore
name: connectEventName,
respond: true,
silent: true,
}).then(this._handleConnectCallbacks);

// @ts-ignore
this.listen(connectEventName, this._handleConnectCallbacks);
}

private _handleConnectCallbacks = async () => {
if (this._connected) {
return;
}
this._connected = true;
this._onConnectCallback.forEach((callback) => {
callback();
});
this._onConnectCallback.clear();
};

private _connected = false;

private _onConnectCallback = new Set<ClientCallback>();

onConnect(callback: ClientCallback) {
if (this._connected) {
return callback();
}
this._onConnectCallback.add(callback);
return () => {
this._onConnectCallback.delete(callback);
};
}
}

Expand Down

0 comments on commit 5cb27f4

Please sign in to comment.