コンテンツにスキップ

map

ソースから発行される各値をマッピング関数で変換し、その結果が今持っている値と等しくなければ発行します。

比較は equals を指定しなければ Object.is なので、変わらなかった結果は下流を何も起こしません。イベントを値に変えるときなど、結果を毎回流したい場合は equals: () => false を渡すか mapTo を使ってください。マッピング関数には値だけが渡されます。インデックスが必要なら withIndex を使ってください。

Timeline of observable events13467
map((x) => x % 2)
Timeline of observable events101
// Timeline:
//
// num$ 1 3 4 6 7
// parity$ 1 0 1
//
// Explanation:
// - map transforms each value
// - A result equal to the one held is not emitted
const num$ = source<number>();
const parity$ = num$.pipe(map((x) => x % 2));
const valueHistory: number[] = [];
parity$.subscribe((p) => {
valueHistory.push(p);
});
num$.next(1); // 1
num$.next(3); // still 1: not emitted
num$.next(4); // 0
num$.next(6); // still 0: not emitted
num$.next(7); // 1
assert.deepStrictEqual(valueHistory, [1, 0, 1]);

View source on GitHub