GoogleChromeLabs / comlink

Comlink makes WebWorkers enjoyable.
Apache License 2.0
11k stars 382 forks source link

How to transfer result buffers #641

Closed stevexbritton closed 11 months ago

stevexbritton commented 11 months ago

I'm sure this is a silly question, but how do I transfer, instead of copy, function result values?

const buffer = new Uint8Array([1, 2, 3]).buffer;
const result = await thing(Comlink.transfer(buffer, [buffer]))

If result is also a Uint8Array how do I specify I want it to be transferred and not copied?

Thanks

surma commented 11 months ago

You have to use Comlink.transfer() in the implementation of the function. The caller cannot decide whether to copy or transfer. Only the function itself can. Does that answer your question?

stevexbritton commented 11 months ago

Yes, thanks. I said it was a silly question, I don't know why I didn't think of just wrapping the result value on a Comlink.transfer() call.