Introducing Compute
What is it?
Compute is an extremely simple reactive programming library using Observables.
What's an Observable?
An observable variable is a function, which holds a value. You can get the value by calling the function without any arguments, and you update the value by calling the function with the desired new value.
The useful thing about an observable is that you can choose to be notified every time the value of this observable changes.
Let me illustrate through code
import { observable, onChange } from "compute";
// Create a new observable.
const o1 = observable(42);
// Access the value
console.log(o1()); // Logs 42
// Subscribe to it
const mySubscription = onChange(newValue => console.log(newValue), o1);
// Update the value
o1(84); // Console shows 84
// You won't get notified until the value changes (strict equality).
o1(84); // Nothing happens.
// Stop getting notifications
mySubscription.unsubscribe();
onChange: React to observable value changes
import {observable, onChange} from "compute";
const a = observable(1);
const b = observable(2);
const c = observable(3);
const sum = (x, y, z) => console.log(`The sum is ${x + y + z}`);
onChange(sum, a, b, c); // Nothing happens so far
a(2); // Console shows "The sum is 7"
b(3); // Console shows "The sum is 8"
from(): Define an observable based on the value of other observables
import {observable, onChange, from} from "compute";
const a = observable(1);
const b = observable(2);
const c = observable(3);
const getSum = (...values) => values?.reduce(val, x => x + val, 0);
const sum = from(
getSum,
a,
b,
c,
);
console.log(sum()); // Prints 6
a(2);
console.log(sum()); // Prints 7
// And because sum is an observable, you can subscribe to it.
when(sum, x => console.log(x));
a(3); // Console shows 8
b(3); // Console shows 9
c(0); // Console shows 6
Installation
npm install compute
Source code
Visit https://github.com/akshat1/compute
Caution
As npm will tell you, it has been a long time since Compute was updated and you should most likely not be using it at this time. Additionally, the signals proposal would make this library unnecessary once it lands.
Attribution
Compute is an adaptation of Cell, a library built on top of KnockoutJS observables at
Platfora.