# Observable Alerts

Canonical page: https://www.adaptabletools.com/docs/handbook-alerting-observables

- Observable Alerts fire when a live [Observable Expression](https://www.adaptabletools.com/docs/adaptable-ql-expression-observable/index.md) Rule becomes true
- They are ideal for Alerts that are based on history or time conditions
- Examples include change counts, highs and lows, silence, grid-wide activity, and row-event counts
- The Rule is a **boolean** Expression built from Observable Functions (that use curly braces)

Observable Alerts watch **how** data has changed (or, indeed not changed) in AG Grid over time.

They leverage AdapTable's recorded cell / row history.

Typical use cases for Observable Alerts include:

- a cell has changed 3 times in the last 2 minutes
- a value is at its highest in the last hour
- there have been no ticks for 5 seconds
- a column changed grid-wide N times within a window
- at least N rows were added or removed in a timeframe

See [Observable Expressions](https://www.adaptabletools.com/docs/adaptable-ql-expression-observable/index.md) for full details of the many observable-related functions available

## Observable Functions

There are many Observable Functions available.

The ones which are most commonly used in Alerts are:

| Function | Example Alert Rule |
| --- | --- |
| `CHANGE_COUNT` | `CHANGE_COUNT{[price], WITHIN(5m)} >= 3` — choppy |
| `NO_CHANGES` | `NO_CHANGES{[price], WITHIN(20s)}` — this row has gone quiet |
| `NET_CHANGE` | `NET_CHANGE{[price], WITHIN(1h)} > 10` — large absolute move |
| `PERCENT_CHANGE` | `PERCENT_CHANGE{[price], WITHIN(1h)} > 5` — up more than 5% in the hour |
| `HIGHEST` / `LOWEST` | `[price] = HIGHEST{[price], WITHIN(1d)}` — at the daily high |
| `PREVIOUS` | `[price] > PREVIOUS{[price]}` — higher than the last tick |
| `ROW_AGE` | `ROW_AGE{} < 30s` — row added in the last 30 seconds |
| `ROWS_ADDED` / `ROWS_REMOVED` | `ROWS_ADDED{WITHIN(1m)} >= 3` — burst of adds in a minute |

See [Observable Expressions](https://www.adaptabletools.com/docs/adaptable-ql-expression-observable/index.md) for the full catalogue and timeframes (e.g. `WITHIN`, `LAST_N`, `ALL_ROWS()`)

## Creating Alert Expressions

Observable Functions always return a **value**.

The return value can be of any kind, though it is most commonly a number

However Alert Expressions need to return a boolean - so they trigger if they evaluate as true.

Accordingly, in order to create an Alert Rule, you need 2 steps:

1. create a normal Observable Expression:

```ts
CHANGE_COUNT{[price], WITHIN(5m)}
```

2. Wrap that Observable Expression inside a comparison operation:

```ts [[1, 1, ">= 3"]]
CHANGE_COUNT{[price], WITHIN(5m)} >= 3
```

### Providing Observable Alerts in Initial State

Set `Type: 'Observable'` for live rules. Use `Scope: { All: true }` unless the rule is grid-level only.

Wrap observable functions (curly braces) in a comparison so the rule evaluates to true / false.

Observable alerts default to firing when the rule **becomes** true (`TriggerPolicy.FireOn: 'BecomeTrue'`). See [Alerts Technical Reference](https://www.adaptabletools.com/docs/technical-reference-alerting/index.md).

```ts [[1, 2, "Alert"], [1, 3, "AlertDefinitions"], [1, 6, "Type"], [1, 6, "Observable"], [1, 9, "Scope"], [2, 10, "Rule"], [2, 10, "CHANGE_COUNT"], [2, 20, "Rule"], [2, 20, "HIGHEST"]]
const initialState: InitialState = {
  Alert: {
    AlertDefinitions: [
      {
        Name: 'alert-stars-choppy',
        Type: 'Observable',
        MessageType: 'Info',
        MessageHeader: 'Choppy stars',
        Scope: {All: true},
        Rule: 'CHANGE_COUNT{[github_stars], WITHIN(2m)} >= 3',
        AlertProperties: {
          DisplayNotification: true,
        },
      },
      {
        Name: 'alert-issues-at-high',
        Type: 'Observable',
        MessageType: 'Success',
        Scope: {All: true},
        Rule: "[open_issues_count] = HIGHEST{[open_issues_count], WITHIN(1h)} AND [language] = 'JavaScript'",
        AlertProperties: {
          DisplayNotification: true,
          HighlightCell: true,
        },
      },
    ],
  },
};
```

## Per Row Changes

The most common Observable Alert use case is watching each row's own change history.

**Example: Alerts: Observing Row Changes**

Observable Alerts on per-row history

- This demo showcases 2 Observable Alerts which focus on per-row changes:
  - Tell me if Github Stars has changed 3 times in this row within 2 minutes: `CHANGE_COUNT{[github_stars], WITHIN(2m)} >= 3`
  - Tell me if Open Issues is at its 1-hour high on JavaScript rows: `[open_issues_count] = HIGHEST{[open_issues_count], WITHIN(1h)} AND [language] = 'JavaScript'`

- Click the *Add Star* [Action Column](https://www.adaptabletools.com/docs/handbook-action-column/index.md) button next to `Github Stars`; once it is clicked 3 times in a row, the Info Alert will be triggered
- Click the *Open an Issue* button next to `Open Issues` on a JavaScript row to push it to a new high

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  ActionColumnContext,
  AdaptableOptions,
  CellUpdateRequest,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export function incrementCellValue(
  columnName: string,
  context: ActionColumnContext,
  amount: number = 1
): void {
  const currentItemCount = context.rowNode.data[columnName];
  const cellUpdateRequest: CellUpdateRequest = {
    columnId: columnName,
    newValue: currentItemCount + amount,
    primaryKeyValue: context.primaryKeyValue,
    rowNode: context.rowNode,
  };
  context.adaptableApi.gridApi.setCellValue(cellUpdateRequest);
}

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Observable Alerts Row Changes',
  adaptableStateKey: `${Date.now()}`,
  actionColumnOptions: {
    actionColumns: [
      {
        columnId: 'increaseStars',
        friendlyName: 'Add Star',
        controls: [
          {
            type: 'button',
            label: '+',
            style: {tone: 'neutral', variant: 'raised'},
            onClick: (context: ActionColumnContext) => {
              incrementCellValue('github_stars', context);
            },
          },
        ],
      },
      {
        columnId: 'openIssue',
        friendlyName: 'Open an Issue',
        controls: [
          {
            type: 'button',
            label: '+',
            style: {tone: 'neutral', variant: 'raised'},
            onClick: (context: ActionColumnContext) => {
              incrementCellValue('open_issues_count', context);
            },
          },
        ],
      },
      {
        columnId: 'closeIssue',
        friendlyName: 'Close an Issue',
        controls: [
          {
            type: 'button',
            label: '-',
            style: {tone: 'neutral', variant: 'raised'},
            onClick: (context: ActionColumnContext) => {
              incrementCellValue('open_issues_count', context, -1);
            },
          },
        ],
      },
    ],
  },

  initialState: {
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'increaseStars',
            'license',
            'openIssue',
            'open_issues_count',
            'closeIssue',
          ],
        },
      ],
    },
    Dashboard: {
      ModuleButtons: ['Alert'],
      Tabs: [
        {
          Name: 'Toolbars',
          Toolbars: ['Alert'],
        },
      ],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Alert'],
        },
      ],
    },
    Alert: {
      AlertDefinitions: [
        {
          Name: 'alert-observable-github-stars-change',
          Type: 'Observable',
          MessageType: 'Info',
          MessageHeader: "That's 3 Changes!",
          MessageText: 'Github Stars Changed 3 times in this Row',
          Scope: {All: true},
          Rule: 'CHANGE_COUNT{[github_stars], WITHIN(2m)} >= 3',
          AlertProperties: {
            DisplayNotification: true,
          },
        },
        {
          Name: 'alert-observable-open-issues-count-change',
          Type: 'Observable',
          MessageType: 'Success',
          Scope: {All: true},
          Rule: "[open_issues_count] = HIGHEST{[open_issues_count], WITHIN(1h)} AND [language] = 'JavaScript'",
          AlertProperties: {
            DisplayNotification: true,
          },
        },
      ],
    },
  },
};
```

## Grid-wide Changes

Observable Alerts can also fire based on activitiy across the whole Grid.

This is by done by using the `ALL_ROWS()` keyword.

This is useful when you care about overall activity rather than a single row

**Example: Alerts: Observing Grid Changes**

Observable Alerts on grid-wide history

- This example contains 2 Observable Alerts which operate over the whole Grid:
  - Tell me if Language changed 3 times anywhere in the Grid within 5 minutes - `CHANGE_COUNT{[language], WITHIN(5m), ALL_ROWS()} >= 3`
  - Tell me if Github Stars changed twice within a minute, counting only MIT License rows - `CHANGE_COUNT{[github_stars] WHERE [license] = 'MIT License', WITHIN(1m), ALL_ROWS()} >= 2`

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Observable Alert Grid Changes',
  adaptableStateKey: `${Date.now()}`,
  initialState: {
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'open_issues_count',
          ],
        },
      ],
    },
    Dashboard: {
      ModuleButtons: ['Alert'],
      Tabs: [
        {
          Name: 'Toolbars',
          Toolbars: ['Alert'],
        },
      ],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Alert'],
        },
      ],
    },
    Alert: {
      AlertDefinitions: [
        {
          Name: 'alert-observable-language-change',
          Type: 'Observable',
          MessageType: 'Error',
          Scope: {All: true},
          Rule: 'CHANGE_COUNT{[language], WITHIN(5m), ALL_ROWS()} >= 3',
          AlertProperties: {
            DisplayNotification: true,
          },
        },
        {
          Name: 'alert-observable-github-stars-change',
          Type: 'Observable',
          MessageType: 'Info',
          Scope: {All: true},
          Rule: "CHANGE_COUNT{[github_stars] WHERE [license] = 'MIT License', WITHIN(1m), ALL_ROWS()} >= 2",
          AlertProperties: {
            DisplayNotification: true,
          },
        },
      ],
    },
  },
};
```

## No Changes

Observable Alerts are also ideal for detecting **silence** — when expected ticks stop.

- This is particularly useful if you have ticking data or you expect some changes at some point
- `NO_CHANGES` is the Function for this: it returns a boolean, so it can be the Alert Rule on its own

### No Changes Per Row

Watch one column on each row:

```ts [[2, 2, "NO_CHANGES"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "20s"]]
// Fires per row when that row's price has been quiet for 20 seconds
NO_CHANGES{[price], WITHIN(20s)}
```

Or watch every column on the row with `ANY_COL()`:

```ts [[2, 1, "NO_CHANGES"], [2, 1, "ANY_COL"], [2, 1, "WITHIN"], [4, 1, "20s"]]
NO_CHANGES{ANY_COL(), WITHIN(20s)}
```

### No Changes Per Grid

Add `ALL_ROWS()` for one shared reading across the whole Grid.

```ts [[2, 2, "NO_CHANGES"], [1, 2, "price"], [2, 2, "WITHIN"], [4, 2, "5s"], [2, 2, "ALL_ROWS"]]
// Fires once when no row has changed price in 5 seconds
NO_CHANGES{[price], WITHIN(5s), ALL_ROWS()}
```

- `ANY_COL()` with `ALL_ROWS()` is the usual “feed stalled” pattern — silence anywhere, on any column
- `DisplaySystemStatusMessage` on the Alert writes the same message into the [System Status](https://www.adaptabletools.com/docs/handbook-system-status-message/index.md) bar

```ts [[2, 1, "NO_CHANGES"], [2, 1, "ANY_COL"], [2, 1, "WITHIN"], [4, 1, "10s"], [2, 1, "ALL_ROWS"]]
NO_CHANGES{ANY_COL(), WITHIN(10s), ALL_ROWS()}
```

**Example: Alerts: Observing No Changes**

Silence on the price feed raises a System Status Error

- A live price feed updates `Last` several times a second, and the Column flashes on each tick
- The Alert Rule is `NO_CHANGES{ANY_COL(), WITHIN(2s), ALL_ROWS(), TRIGGER('tick')}`
- `DisplaySystemStatusMessage` is on, so when the Rule fires the [System Status](https://www.adaptabletools.com/docs/handbook-system-status-message/index.md) bar shows an Error

- Watch prices tick and flash
- Click **Simulate system down in 10 secs** — ticking continues
- After 10 seconds the feed stops; 2 seconds of silence later the Error System Status appears
- Click **Resume Feed** to restore the ticks

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  priceFeed.ts
  rowData.ts
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {Quote} from './rowData';
import {simulateSystemDownIn10Seconds, startPriceFeed} from './priceFeed';

export const adaptableOptions: AdaptableOptions<Quote> = {
  primaryKey: 'id',
  adaptableId: 'Observable Alert No Changes',
  expressionOptions: {
    liveRefreshIntervalMs: 1000,
  },
  dashboardOptions: {
    customToolbars: [
      {
        name: 'priceFeed',
        title: 'Price Feed',
        toolbarButtons: [
          {
            label: 'Simulate system down in 10 secs',
            onClick: (_button, context) =>
              simulateSystemDownIn10Seconds(context.adaptableApi),
            buttonStyle: {tone: 'warning', variant: 'raised'},
          },
          {
            label: 'Resume Feed',
            onClick: (_button, context) => {
              startPriceFeed(context.adaptableApi);
              context.adaptableApi.systemStatusApi.setSuccessSystemStatus(
                'Price feed restored'
              );
            },
            buttonStyle: {tone: 'success', variant: 'raised'},
          },
        ],
      },
    ],
  },
  initialState: {
    Dashboard: {
      ModuleButtons: ['Alert', 'SystemStatus'],
      Tabs: [
        {
          Name: 'Toolbars',
          Toolbars: ['Alert', 'priceFeed', 'SystemStatus'],
        },
      ],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Alert', 'SystemStatus'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Alert: {
      AlertDefinitions: [
        {
          Name: 'price-feed-silence',
          Type: 'Observable',
          MessageType: 'Error',
          MessageHeader: 'Price feed down',
          MessageText: 'No cell has changed anywhere in the Grid for 2 seconds',
          Scope: {All: true},
          Rule: "NO_CHANGES{ANY_COL(), WITHIN(2s), ALL_ROWS(), TRIGGER('tick')}",
          AlertProperties: {
            DisplayNotification: true,
            DisplaySystemStatusMessage: true,
          },
        },
      ],
    },
    FlashingCell: {
      FlashingCellDefinitions: [
        {
          Name: 'flash-last',
          Type: 'Change',
          Scope: {ColumnIds: ['last']},
          Rule: 'ANY_CHANGE()',
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'price-format',
          Scope: {ColumnIds: ['last']},
          DisplayFormat: {Formatter: 'NumberFormatter', Options: {FractionDigits: 2}},
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Live Prices',
      Layouts: [
        {
          Name: 'Live Prices',
          TableColumns: ['symbol', 'name', 'sector', 'last', 'volume'],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/priceFeed.ts`**

```ts
import {AdaptableApi} from '@adaptabletools/adaptable';
import {Quote} from './rowData';

const TICK_MS = 250;
const STOP_AFTER_MS = 10_000;

let intervalId: ReturnType<typeof setInterval> | undefined;
let stopTimerId: ReturnType<typeof setTimeout> | undefined;
let stopScheduled = false;

const randomBetween = (min: number, max: number) => Math.random() * (max - min) + min;

const tickOnce = (api: AdaptableApi) => {
  const rows = api.gridApi
    .getVisibleRowNodes()
    .map(node => node.data as Quote)
    .filter(row => row);
  if (!rows.length) {
    return;
  }
  const row = rows[Math.floor(Math.random() * rows.length)];
  const last = Math.round(row.last * (1 + randomBetween(-0.004, 0.004)) * 100) / 100;
  const volume = row.volume + Math.round(randomBetween(500, 20_000));
  api.gridApi.updateGridData([{...row, last, volume}]);
};

export const startPriceFeed = (api: AdaptableApi) => {
  stopPriceFeed();
  stopScheduled = false;
  intervalId = setInterval(() => tickOnce(api), TICK_MS);
};

export const stopPriceFeed = () => {
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = undefined;
  }
  if (stopTimerId) {
    clearTimeout(stopTimerId);
    stopTimerId = undefined;
  }
};

export const simulateSystemDownIn10Seconds = (api: AdaptableApi) => {
  if (stopScheduled || !intervalId) {
    return;
  }
  stopScheduled = true;
  api.systemStatusApi.setInfoSystemStatus(
    'Simulating system down in 10 seconds',
    'Prices will keep ticking until the feed stops'
  );
  stopTimerId = setTimeout(() => {
    stopPriceFeed();
  }, STOP_AFTER_MS);
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';
import {startPriceFeed} from './priceFeed';

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  startPriceFeed(adaptableApi);
  adaptableApi.systemStatusApi.setSuccessSystemStatus('Price feed live');
};
```

**`src/rowData.ts`**

```ts
export interface Quote {
  id: number;
  symbol: string;
  name: string;
  sector: string;
  last: number;
  volume: number;
}

export const rowData: Quote[] = [
  {id: 1, symbol: 'AAPL', name: 'Apple', sector: 'Technology', last: 189.2, volume: 1_250_000},
  {id: 2, symbol: 'MSFT', name: 'Microsoft', sector: 'Technology', last: 415.5, volume: 980_000},
  {id: 3, symbol: 'NVDA', name: 'NVIDIA', sector: 'Technology', last: 875.0, volume: 2_400_000},
  {id: 4, symbol: 'AMZN', name: 'Amazon', sector: 'Consumer', last: 178.6, volume: 1_100_000},
  {id: 5, symbol: 'TSLA', name: 'Tesla', sector: 'Consumer', last: 248.3, volume: 1_900_000},
  {id: 6, symbol: 'JPM', name: 'JPMorgan Chase', sector: 'Financials', last: 198.7, volume: 640_000},
  {id: 7, symbol: 'GS', name: 'Goldman Sachs', sector: 'Financials', last: 452.3, volume: 310_000},
  {id: 8, symbol: 'XOM', name: 'Exxon Mobil', sector: 'Energy', last: 118.2, volume: 720_000},
  {id: 9, symbol: 'CVX', name: 'Chevron', sector: 'Energy', last: 156.4, volume: 540_000},
  {id: 10, symbol: 'UNH', name: 'UnitedHealth', sector: 'Healthcare', last: 528.0, volume: 410_000},
];
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';
import {Quote} from './rowData';

export const columnDefs: ColDef<Quote>[] = [
  {field: 'id', hide: true, cellDataType: 'number'},
  {field: 'symbol', headerName: 'Symbol', cellDataType: 'text'},
  {field: 'name', headerName: 'Name', cellDataType: 'text'},
  {field: 'sector', headerName: 'Sector', cellDataType: 'text'},
  {field: 'last', headerName: 'Last', cellDataType: 'number', type: 'rightAligned'},
  {field: 'volume', headerName: 'Volume', cellDataType: 'number', type: 'rightAligned'},
];
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {columnDefs} from './columnDefs';
import {rowData, Quote} from './rowData';

export const gridOptions: GridOptions<Quote> = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: false,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  columnMenu: 'new',
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

## Row Change Counts

AdapTable provides a [Row Change Alert](https://www.adaptabletools.com/docs/handbook-alerting-row-change/index.md) which is a specialist Alert Type.

This common use case occurs when Rows are added or removed from the Grid.

However it is possible to extend these with fully-powered Observable Expressions — e.g. alert only when a specific **number** of rows have been added within a **timeframe**:

```ts [[2, 2, "ROWS_ADDED"], [2, 2, "WITHIN"], [4, 2, "1m"]]
 // Tell me if more than 10 rows were added in the last minute
 ROWS_ADDED{WITHIN(1m)} > 10
```

**Example: Alerts: Row Add Burst**

Observable Alert when several rows are added in a window

- Alert Type is `Observable` (not Row Change)
- Rule: `ROWS_ADDED{WITHIN(30s)} >= 3` — fires when at least 3 rows are added within 30 seconds
- Unlike a [Row Change Alert](https://www.adaptabletools.com/docs/handbook-alerting-row-change/index.md), this does **not** fire on every single add — only when the count in the window crosses the threshold

- Click the **Add Row** Dashboard button three times (within 30 seconds) and note the Warning Alert

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableButton,
  AdaptableOptions,
  DashboardButtonContext,
  DataUpdateConfig,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

function createDemoRow(rowCount: number): WebFramework {
  const id = Math.floor(Math.random() * (1000000 - 5000 + 1) + 200000);
  return {
    id,
    name: `New Repo ${rowCount + 1}`,
    description: 'Added for Observable ROWS_ADDED demo',
    created_at: new Date().toDateString(),
    updated_at: new Date().toDateString(),
    pushed_at: new Date().toDateString(),
    github_stars: 100,
    language: 'TypeScript',
    open_issues_count: 0,
    license: 'MIT License',
    github_watchers: 10,
    topics: ['demo'],
    has_projects: true,
    has_wiki: true,
    has_pages: false,
    closed_issues_count: 0,
    open_pr_count: 0,
    closed_pr_count: 0,
    week_issue_change: 0,
  };
}

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Observable Alert Row Added Count',
  adaptableStateKey: `${Date.now()}`,
  expressionOptions: {
    liveRefreshIntervalMs: 1000,
  },
  notificationsOptions: {
    position: 'TopCenter',
  },
  dashboardOptions: {
    customDashboardButtons: [
      {
        label: 'Add Row',
        onClick: (
          _button: AdaptableButton<DashboardButtonContext>,
          context: DashboardButtonContext
        ) => {
          const rowCount = context.adaptableApi.gridApi.getRowCount();
          const dataUpdateConfig: DataUpdateConfig = {
            runAsync: true,
            addIndex: 0,
          };
          context.adaptableApi.gridApi.addGridData(
            [createDemoRow(rowCount)],
            dataUpdateConfig
          );
        },
        buttonStyle: {
          variant: 'raised',
          tone: 'info',
        },
      },
    ],
  },
  initialState: {
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: ['name', 'language', 'license', 'github_stars', 'has_wiki'],
        },
      ],
    },
    Dashboard: {
      ModuleButtons: ['Alert'],
      Tabs: [
        {
          Name: 'Toolbars',
          Toolbars: ['Alert'],
        },
      ],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Alert'],
        },
      ],
    },
    Alert: {
      AlertDefinitions: [
        {
          Name: 'alert-observable-rows-added-burst',
          Type: 'Observable',
          MessageType: 'Warning',
          MessageHeader: 'Busy adds!',
          MessageText: '3 or more rows were added in the last 30 seconds',
          Scope: {All: true},
          Rule: 'ROWS_ADDED{WITHIN(30s)} >= 3',
          AlertProperties: {
            DisplayNotification: true,
          },
        },
      ],
    },
  },
};
```

## Suspending Observable Alerts

When an Observable Alert is suspended, the subscription is **removed**.

It will then be re-created when unsuspended.

- This means that any changes in the data during the Alert's suspension are **not** observed
- The count / watch starts again from scratch (rather than continues) when the Alert is unsuspended
