spark.createSelfRpc
function createSelfRpc(): RpcCreate an RPC instance for the current Web Worker context.
Used in Web Workers to set up RPC handlers and listen for messages from the parent thread.
Equivalent to: new Rpc({ target: self, origin: '*' })
This should typically be called once at the worker entry point to set up the communication channel with the parent.
Returns
Rpc– RPC instance configured for worker contextExamples
// In a Web Worker (worker.js):
import torch from '@torchjsorg/torch.js';
import * as spark from '@torchjsorg/spark';
const rpc = createSelfRpc();
// Register handlers for parent's RPC calls
rpc.handle('train', async (params) => {
const model = torch.nn.Sequential([...]);
// ... training logic
return { loss: 0.5, accuracy: 0.95 };
});
// Send updates to parent
rpc.notify('worker.ready', { loaded: true });
// Handle control messages
rpc.handle('control', (command) => {
if (command === 'stop') {
// Stop training
}
});See Also
- createWorkerRpc - Create RPC to worker (from main thread)
- createParentRpc - Create RPC to parent (from iframe)