value-enhancer


A tiny library to enhance value with reactive wrapper.
Install
npm add value-enhancer
Why
The goal of this lib is to bring reactivity to values like MobX but without the implicit-cast magic. It is like RxJS but trimmed and simplified with the focus on value changes instead of async operations which resulted in much smaller codebase.
Usage
import { Val, combine, derive } from "value-enhancer";
const val = new Val(2);
console.log(val.value);
val.setValue(3);
console.log(val.value);
val.subscribe(value => console.log(`subscribe: ${value}`));
val.reaction(value => console.log(`reaction: ${value}`));
val.setValue(3);
val.setValue(4);
const derived = derive(val, value => value * 3);
console.log(derived.value);
derived.subscribe(value => console.log(`derived: ${value}`));
const combined = combine([val, derived], ([val, derived]) => val + derived);
console.log(combined.value);
combined.subscribe(value => console.log(`combined: ${value}`));
val.setValue(5);
setValue
may carry any type of extra info via meta
param.
val.subscribe((value, meta) => console.log(value, meta));
val.setValue(5, { source: "remote" });
Bind Instance
Val can be bound to a object via withValueEnhancer
.
import type { ValEnhancedResult } from "value-enhancer";
import { Val, withValueEnhancer } from "value-enhancer";
interface Obj extends ValEnhancedResult<{ count: Val<number> }> {}
class Obj {
constructor() {
withValueEnhancer(this, {
count: new Val(2),
});
console.log(this.count, this.setCount, this._count$);
}
addOne(): void {
this.setCount(this.count + 1);
}
}