How to compute a new result whenever any of the given source streams changes? #6626
-
If I need an observable that computes result depending on other result - I will very often use const a = new Subject();
const b = new Subject();
// Should compute a + b from latest a and b values
const abSum = combineLatest([a, b]).pipe(map(([a, b]) => a + b));
// Should compute `a + 2 * b` when a or b change
const abbSum = combineLatest([abSum, b]).pipe(map(([a, b]) => a + b));
abbSum.subscribe((x) => {
console.log(x);
});
a.next(5);
b.next(7);
// Logs 19 (which is expected `5 + 7 * 2 = 19`)
b.next(3);
// Logs 15 - and then 11. But 15 is basically an invalid state to me Perhaps anyone has encountered a similar issue, and has an idea how to avoid the invalid intermediate state, when using too many combineLatest together? In my case - the final sum should be the same as |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
One solution I can imagine is to rewrite it as: const abbSum = abSum.pipe(withLatestFrom(b), map(([a, b]) => a + b)); But this requires me to know that |
Beta Was this translation helpful? Give feedback.
-
Just so this can be closed as "answered", let me mark the IMHO correct approach in a separate comment: const a = cold('a', { a: 5 });
const b = cold('a-b', { a: 7, b: 3 });
const abSum = combineLatest([a, b]).pipe(map(([a, b]) => a + b));
const abbSum = combineLatest([abSum, b]).pipe(
auditTime(0, asapScheduler),
map(([a, b]) => a + b)
);
expectObservable(abbSum).toBe('a-b', { a: 19, b: 11 }); // PASS |
Beta Was this translation helpful? Give feedback.
Just so this can be closed as "answered", let me mark the IMHO correct approach in a separate comment: