Remote / Totals over a loaded list

What it costs, and when it adds everything up again

Each call compares what it worked from last time with the Model it is given, and follows only the rows that changed:

  • a row the server wrote, a live patch, a pending write and its rollback, or a row moving in or out of Unpaid move a sum or count by one difference, and an every or any by one count;
  • a min or max folds a new or changed row in, and reads the counted rows again only when the row holding the smallest (or largest) value leaves or loses it;
  • a merged page or a refetch compares the list's keys and judges only rows it had not judged.

When it cannot trace the changes to rows, it reads the loaded list again and updates the aggregate from the differences. This can happen after restoring a snapshot, changing the viewer, passing an older Model, or leaving more than a thousand store writes between reads. The same applies when a filter or selection reads related rows and the store changes. If a sum temporarily overflows while applying changes, it evaluates the final rows to check whether the total fits.

While any write in the domain is pending, each change to the store also walks the list's keys to see which rows are shown, as the list's own read does to place pending rows. No row is judged or added again unless it changed, so the aggregate is handed one row; the walk itself grows with the list.

Define each aggregate once, at module level. The kept total belongs to the aggregate value, the domain, the list and the query, so an aggregate made inside the view is a new one each render and is added up from nothing each time. Define the last argument once too (const unpaidOnly = { where: Unpaid, input: {} }): what the list and the query say is worked out once for each such object, and again for a new one, though the kept total is the same.

Keep the rows for display

Pass Maintained.list to keep the selected rows in the loaded connection's order. The array keeps its identity while the result rows and their order stay the same. where picks which rows to keep.

ts
import { Maintained } from 'foldkit-remote/maintained'

const unpaidRows = Maintained.value(Data, model, invoices, Maintained.list, { where: Unpaid, input: {} })
unpaidRows.value // the loaded unpaid invoice rows