Add cleanup() to the API.
This commit is contained in:
parent
a01a9a53b7
commit
da86fc6045
@ -37,6 +37,7 @@ export function WorkerPortal(context, worker, serialize) {
|
||||
? (type, destination, id, params) => serialize(type, destination, id, params, tryJSON)
|
||||
: tryJSON;
|
||||
let callCount = 0;
|
||||
let enabled = false;
|
||||
|
||||
function post(type, id, destination, params) {
|
||||
_worker.postMessage(_serialize(type, destination, id, params));
|
||||
@ -85,6 +86,9 @@ export function WorkerPortal(context, worker, serialize) {
|
||||
function injectionPointFactory(fnId, callbackFactory) {
|
||||
return () =>
|
||||
new Promise((resolve, reject) => {
|
||||
if (!enabled) {
|
||||
reject(new Error('Portal disabled'));
|
||||
}
|
||||
const id = callCount;
|
||||
callCount += 1;
|
||||
responseMap.set(id, [callbackFactory ? callbackFactory(resolve) : resolve, reject]);
|
||||
@ -98,17 +102,36 @@ export function WorkerPortal(context, worker, serialize) {
|
||||
linkedFunctionNames.forEach((fnName, index) => {
|
||||
externalInterface[fnName] = injectionPointFactory(index);
|
||||
});
|
||||
if (!isWorker()) {
|
||||
externalInterface._cleanup = injectionPointFactory(linkedFunctionNames.length, resolve =>
|
||||
resolve(cleanup())
|
||||
);
|
||||
}
|
||||
enabled = true;
|
||||
resolve(externalInterface);
|
||||
return contextIndex;
|
||||
};
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
enabled = false;
|
||||
_worker.removeEventListener('message', dispatcher);
|
||||
for (let key of responseMap.keys()) {
|
||||
try {
|
||||
responseMap.get(key)[1](new Error('Portal cleanup called.'));
|
||||
} catch (e) {}
|
||||
}
|
||||
}
|
||||
|
||||
_worker.addEventListener('message', dispatcher);
|
||||
|
||||
return isWorker()
|
||||
? new Promise(resolve => {
|
||||
contextIndex.splice(0, 0, '__init');
|
||||
context.__init = resolveExternalInterfaceFactory(resolve);
|
||||
})
|
||||
: injectionPointFactory(0, resolveExternalInterfaceFactory)(contextIndex);
|
||||
if (isWorker()) {
|
||||
return new Promise(resolve => {
|
||||
contextIndex.splice(0, 0, '__init', '__cleanup');
|
||||
context.__init = resolveExternalInterfaceFactory(resolve);
|
||||
context.__cleanup = cleanup;
|
||||
});
|
||||
}
|
||||
|
||||
return injectionPointFactory(0, resolveExternalInterfaceFactory)(contextIndex);
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user