コンテンツにスキップ

derive

複数の Observable の最新値から 1 つの値を派生します。それらの値を引数として project を呼び出す 1 つの Observable で、結果が保持している値と等しくなければ発行します。

いずれかの親が発行するたびに、すべての親が値を持った後に限って発行する点は combine と同じです。ただし combine(parents).pipe(map(fn)) が 2 つの Observable と更新ごとのタプルを要するのに対し、derive は 1 つで、値を引数として渡します(project が残余引数で受けると、そこで配列が作られます)。比較は equals を指定しない限り Object.is です。

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