Skip to content

derive

Derives one value from the latest values of several observables: one observable that calls project with them, as arguments, and emits the result unless it equals the one already held.

It emits once every parent has a value, and then whenever any of them emits, as combine does; but where combine(parents).pipe(map(fn)) is two observables and a tuple per update, derive is one, and passes the values as arguments (a rest parameter in project collects them into an array again). The comparison is Object.is unless equals says otherwise.

Timeline of observable events100120Timeline of observable events23
derive((p, q) => p * q)
Timeline of observable events200240360
// Timeline:
//
// price$ 100 120
// quantity$ 2 3
// total$ 200 240 360
//
// Explanation:
// - derive waits for every parent to have a value
// - Then calls the projection with their latest values whenever one emits
const price$ = source<number>();
const quantity$ = source<number>();
const total$ = derive(
[price$, quantity$],
(price, quantity) => price * quantity,
);
const totalHistory: number[] = [];
total$.subscribe((total) => {
totalHistory.push(total);
});
price$.next(100); // nothing yet: quantity$ has no value
quantity$.next(2); // 200
price$.next(120); // 240
quantity$.next(3); // 360
assert.deepStrictEqual(totalHistory, [200, 240, 360]);

View source on GitHub