Assuming I have a source stream of objects as follows:
source$ = from([{ id: 1, cost: 10},{ id: 2, cost: 5},{ id: 3, cost: 3},{ id: 4, cost: 10}])
In the derived observable I would like maintain an additional property with a running sum of the cost
// Expected derived stream
{ id: 1, cost: 10, totalCost: 10}
{ id: 2, cost: 5, totalCost: 15}
{ id: 3, cost: 3, totalCost: 18}
{ id: 4, cost: 10, totalCost: 28}
How could it be achieved with rxjs?
I managed to find this solution:
import { from } from "rxjs";
import {scan} from "rxjs/internal/operators";
let source$ = from([{ id: 1, cost: 10},{ id: 2, cost: 5},{ id: 3, cost: 3},{ id: 4, cost: 10}]);
source$
.pipe(
scan((acc,curr) => {
return {...curr, totalCost: acc.totalCost + curr.cost}
}, {totalCost:0})
)
.subscribe(console.log)