BACK
Use casesDirty diff — send only the changed fields
Use cases · 13

Dirty diff — send only the changed fields

Pattern

A form has 20 fields; the user changed two. We want to send the server only those two fields, not the whole form — a PATCH instead of a PUT. Cheaper, safer (we won't overwrite others' changes), and cleaner in the logs.

The problem it solves

To build a patch, you compare "before" with "after". Imperatively, that means holding the previous state in an external variable and remembering to update it. It's easy to get an empty patch after a programmatic reset, or to send extra fields.

Operators and why they matter

  • startWith — sets the baseline (the form's initial state) that the first change compares against.
  • pairwise — hands you the pair [previous, current] without external variables. The state lives inside the stream.
  • map — builds an object from only the keys where previous !== current.
  • filter — drops empty patches so no meaningless PATCH requests reach the backend.

Gotchas

  • distinctUntilChanged() without a custom comparator is useless on forms — Angular creates a new form-value object on every change, so a reference comparison always returns false.
  • For deeply nested forms, a naive key-based diff won't work — you need a deep diff or normalization.
  • After a successful save you must update the baseline, or the next diff will be computed against the old version.

What you get

Every meaningful form change turns into a minimal payload for the PATCH endpoint. Perfect for auditing too.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...