Skip to content

Instantly share code, notes, and snippets.

@domenic
Created February 14, 2017 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domenic/e1e2238f1447e6f6783f1fba3ee601a6 to your computer and use it in GitHub Desktop.
Save domenic/e1e2238f1447e6f6783f1fba3ee601a6 to your computer and use it in GitHub Desktop.
Service worker stream transferring 2
"use strict";
const worker = new Worker("worker.js");
self.onfetch = e => {
e.respondWith(new Promise(resolve => {
const guid = generateGUID();
worker.addEventListener("message", function messageListener({ data: { readableStream, messageId } }) {
if (messageId !== guid) {
return;
}
worker.removeEventListener("message", messageListener);
resolve(new Response(readableStream));
});
worker.postMessage(guid);
});
};
"use strict";
self.onmessage = ({ data: messageId, source }) => {
const readableStream = new ReadableStream({
start(controller) {
// These can be done asynchronously if you want.
controller.enqueue(new Uint8Array([1, 2, 3]));
controller.close();
}
});
source.postMessage({ readableStream, messageId }, [readableStream]);
// readableStream has now been transferred/neutered/detached.
// This means that readableStream.getReader() will never work anymore in this thread.
// However, we as the creator of the stream can still *enqueue data into it*; it's just
// that the UA has an exclusive lock on reading data out of it, for the purpose of transferring
// it over to the service worker.
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment