> ## Documentation Index
> Fetch the complete documentation index at: https://iii.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Reactive State Pattern

> Run a function each time a piece of state changes, by observing state::on-changed.

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`.

> [tab] Node / TypeScript
>
> ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> type StateChange = {
>   event_type: "state:created" | "state:updated" | "state:deleted";
>   scope: string;
>   key: string;
>   old_value: unknown;
>   new_value: unknown;
> };
>
> worker.registerFunction("orders::notify-status-change", async ({ input }: Observed<StateChange>) => {
>   await notifyCustomer(input.new_value);
>   return null;
> });
>
> // When orders/status changes, run orders::notify-status-change with the change.
> worker.observe(
>   {
>     function_id: "state::on-changed",
>     filters: { "input.scope": { $eq: "orders" }, "input.key": { $eq: "status" } },
>     capture: ["input"],
>   },
>   "orders::notify-status-change",
> );
> ```

> [tab] Python
>
> ```python theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> def notify_status_change(observed: dict) -> None:
>     notify_customer(observed["input"]["new_value"])
>
> worker.register_function("orders::notify-status-change", notify_status_change)
>
> # When orders/status changes, run orders::notify-status-change with the change.
> worker.observe(
>     {
>         "function_id": "state::on-changed",
>         "filters": {"input.scope": {"$eq": "orders"}, "input.key": {"$eq": "status"}},
>         "capture": ["input"],
>     },
>     "orders::notify-status-change",
> )
> ```

> [tab] Rust
>
> ```rust theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> use iii_sdk::{Capture, Error, Observed, RegisterFunction, Source};
> use serde_json::{Value, json};
>
> worker.register_function(
>     "orders::notify-status-change",
>     RegisterFunction::new(|observed: Observed<Value>| {
>         let change = observed.input.unwrap_or_default();
>         notify_customer(&change["new_value"]);
>         Ok::<_, Error>(())
>     }),
> );
>
> // When orders/status changes, run orders::notify-status-change with the change.
> worker.observe(
>     Source::function("state::on-changed")
>         .filters(json!({ "input.scope": { "$eq": "orders" }, "input.key": { "$eq": "status" } }))
>         .capture([Capture::Input]),
>     "orders::notify-status-change",
> );
> ```

> [tab] Go
>
> ```go theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
> worker.RegisterFunction("orders::notify-status-change", func(ctx context.Context, data json.RawMessage) (any, error) {
>     var observed struct {
>         Input struct {
>             NewValue json.RawMessage `json:"new_value"`
>         } `json:"input"`
>     }
>     if err := json.Unmarshal(data, &observed); err != nil {
>         return nil, err
>     }
>     return nil, notifyCustomer(ctx, observed.Input.NewValue)
> })
>
> // When orders/status changes, run orders::notify-status-change with the change.
> if _, err := worker.Observe(iii.Source{
>     FunctionID: "state::on-changed",
>     Filters: iii.Filters{
>         "input.scope": iii.Op{"$eq": "orders"},
>         "input.key":   iii.Op{"$eq": "status"},
>     },
>     Capture: []iii.Capture{iii.CaptureInput},
> }, "orders::notify-status-change"); err != nil {
>     log.Fatal(err)
> }
> ```

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](https://iii.dev/docs/reference/filters.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.