Coder Social home page Coder Social logo

comlink's Introduction

Comlink

Comlink’s goal is to make WebWorkers enjoyable. Comlink removes the mental barrier of thinking about postMessage and hides the fact that you are working with workers.

Note: Comlink’s goal is to be a building-block for higher-level abstraction libraries. For example, take a look at Clooney.

// main.js
const MyClass = Comlink.proxy(new Worker("worker.js"));
// `instance` is an instance of `MyClass` that lives in the worker!
const instance = await new MyClass();
await instance.logSomething(); // logs “myValue = 42”
// worker.js
const myValue = 42;
class MyClass {
  logSomething() {
    console.log(`myValue = ${myValue}`);
  }
}
Comlink.expose(MyClass, self);

Browsers support & bundle size

Chrome 56+ Edge 15+ Firefox 52+ Opera 43+ Safari 10.1+ Samsung Internet 6.0+

Browsers without ES6 Proxy support can use the proxy-polyfill.

Size: ~3.9k, ~1.6k gzip’d

Introduction

WebWorkers are a web API that allow you to run code in a separate thread. To communicate with another thread, WebWorkers offer the postMessage API. You can send messages in form of transferable JavaScript objects using myWorker.postMessage(someObject), triggering a message event inside the worker.

Comlink turns this messaged-based API into a something more developer-friendly: Values from one thread can be used within the other thread (and vice versa) just like local values.

Comlink can be used with anything that offers postMessage like windows, iframes and ServiceWorkers.

Download

You can download Comlink from the dist folder. Alternatively, you can install it via npm

$ npm install --save comlinkjs

or use a CDN like delivrjs:

https://cdn.jsdelivr.net/npm/[email protected]/umd/comlink.js

Examples

There’s a collection of examples in the examples directory.

API

The Comlink module exports 3 functions:

Comlink.proxy(endpoint)

Returns the value that is exposed on the other side of endpoint.

proxy creates an ES6 proxy and sends all operations performed on that proxy through endpoint. endpoint can be a Window, a Worker or a MessagePort.* The other endpoint of the channel should be passed to Comlink.expose.

If you invoke function, all parameters will be structurally cloned or transferred if they are transferable. If you want to pass a function as a parameters (e.g. callbacks), make sure to use proxyValue (see below). Same applies to the return value of a function.

*) Technically it can be any object with postMessage, addEventListener and removeEventListener.

Comlink.expose(obj, endpoint)

Exposes obj to endpoint. Use Comlink.proxy on the other end of endpoint.

expose is the counter-part to proxy. It listens for RPC messages on endpoint and applies the operations to obj. Return values of functions will be structurally cloned or transfered if they are transferable.

Comlink.proxyValue(value)

Makes sure a parameter or return value is proxied, not copied.

By default, all parameters to a function that are not transferable are copied (structural clone):

// main.js
const api = Comlink.proxy(new Worker("worker.js"));
const obj = { x: 0 };
await api.setXto4(obj);
console.log(obj.x); // logs 0

The worker receives a copy of obj, so any mutation of obj done by the worker won’t affect the original object. If the value should not be copied but instead be proxied, use Comlink.proxyValue:

- await api.setXto4(obj);
+ await api.setXto4(Comlink.proxyValue(obj));

console.log(obj.x) will now log 4.

Keep in mind that functions cannot be copied. Unless they are used in combination with Comlink.proxyValue, they will get discarded during copy.


License Apache-2.0

comlink's People

Contributors

bclinkinbeard avatar dylang avatar gruns avatar lacolaco avatar michael42 avatar notwoods avatar philippotto avatar renovate-bot avatar renovate[bot] avatar robwormald avatar ronhe avatar surma avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.