Skip to main content
When a function should run each time a piece of state changes, observe state::on-changed. The state worker calls state::on-changed after every committed write, so each write runs the observer’s target. Filters on input.scope and input.key select the scope and key to watch. The target is a function like any other.

When to use this pattern

When the action is conceptually “whenever this data changes, do this”, instead of “on schedule” or “on demand”. Examples: rebuild a derived index when its source state changes, fan out a notification when a user record updates, propagate a calculated value into another scope when its inputs move.

Structure

  1. A state worker holds the source-of-truth state.
  2. A function in some worker handles the change (compute a derived value, send a notification, etc.).
  3. An observer of state::on-changed, with filters on input.scope and input.key, runs that function after each write to that scope and key.

Example

When the status key in the orders scope changes, run orders::notify-status-change with the change. capture: ["input"] gives the target the change document as the payload’s input.
The change document has event_type (state:created, state:updated, or state:deleted), scope, key, old_value, and new_value. old_value is null for a created key and new_value is null for a deleted one. Filters can read any of them, for example { "input.new_value.status": { "$eq": "shipped" } } to run the target only when an order ships. The target runs after the write commits. A target that fails does not roll the write back. The state worker’s read and write functions are documented in that worker’s Worker Docs. For the filter operators, see Filters.