@wix/editor-platform-transport
v1.10.0
Published
- Browser – Worker – Browser - Browser – Frame – Browser
Downloads
691
Maintainers
Keywords
Readme
Communication between threads
- Browser – Worker – Browser
- Browser – Frame – Browser
🏆🏆🏆
- Transferred API completely copies the transferred objects, so no proxies. This allows to correctly decorate received APIs.
- No additional utils needed, like
comlink.wrap
orcomlink.proxy
- Supports passing promises and callbacks between threads without wrapping it with additional decorators
- Supports catching errors between threads (see src/demo)
- Super small ~3kb
Worker
import {ConsumerChannel} from '@wix/editor-platform-transport';
const channel = new ConsumerChannel();
class WorkerAPI {
type = 'WORKER_API';
functionWithCallback(cb: Function) {
cb(new Promise(resolve => {
setTimeout(() => {
resolve('xxx')
}, 1000)
}));
}
}
channel.expose(new WorkerAPI());
Browser
import {HostChannel} from '@wix/editor-platform-transport';
const worker = new Worker('../dist/statics/demo/worker.js');
const channel = new HostChannel(worker);
channel.recieve<WorkerAPI>('WORKER_API', async api => {
/**
* api - object, exposed from the worker
* it is shape in the main thread is exactly the same as in the worker,
* so we can easyly decorate it or proxify, for example for tracing
*/
await api.functionWithCallback(async (promiseFromWorker) => {
console.log('main-thread', await promiseFromWorker)
})
})
This example will output `'main-thread xxx' after 1sec.
Expose Multiple APIs
import {ConsumerChannel} from '@wix/editor-platform-transport';
const channel = new ConsumerChannel();
class WorkerAPI {
type = 'WORKER_API';
}
class ApplicationAPI {
type = 'APPLICATION_API';
}
channel.expose(new WorkerAPI());
channel.expose(new ApplicationAPI());