Skip to content

Derived

From.derived computes a value based on the value of one or more reactives. If one of the sources changes, the computation happens again. This is a bit like a spreadsheet, setting up a one-way dependency between sources.

To use, pass in a function to compute the output value, along with an object containing the source reactives.

The compute function takes in an object, with properties the same as the sources. That is, if you give a source under property ‘hello’, you’ll get a value object with property ‘hello’ with the value of that source.

For example, we can make a ‘sum’ reactive that outputs the sum of two other reactives, emitting a value whenever one of them changes.

const sources = {
a: Rx.From.number(0),
b: Rx.From.number(0)
};
const sum = Rx.From.derived({a, b} => { // note the destructuring of a & b
return a + b
}, sources);
sum.onValue(v => {
console.log(`Sum: ${sum}`);
})
a.set(10);
// `Sum: 10`
b.set(2);
// `Sum: 12`