Skip to content

Batching, Hooks, and Computed Values

Three tools for the store beyond a single action: a batch makes several actions reach listening views as one, a hook runs code after an action, and a computed value derives something from the state once for every view that reads it.

Several Changes as One

Animation: Kael's server settings panel, drawn twice: on the left Reset All dispatches its four changes one by one, on the right inside self.batch(). Both panels show French, Light, Off, and Weekly. Kael clicks Reset All. On the left the panel redraws after every dispatch: the first request answers the click with Language back to English, then three message edits each put one more setting back, until it shows English, Dark, On, and Daily. On the right the panel redraws once: one request answers the click with all four settings back.

A settings panel whose Reset All button puts four settings back to their defaults:

import discord

from cascadeui import StatefulButton, StatefulLayoutView, card, cascade_reducer, read_slot

DEFAULTS = {"language": "English", "theme": "Dark", "pings": "On", "digest": "Daily"}


@cascade_reducer("SETTING_SET")
def set_setting(action, state):
    guild = state["application"].setdefault("settings", {}).setdefault(action["payload"]["guild"], {})
    guild[action["payload"]["key"]] = action["payload"]["value"]
    return state


class SettingsPanel(StatefulLayoutView):
    subscribed_actions = {"SETTING_SET"}

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.build_ui()

    def build_ui(self):
        saved = read_slot(self.state_store.state, "settings", str(self.guild_id), default={})
        settings = {**DEFAULTS, **saved}
        self.clear_items()
        self.add_item(card("## Server Settings", *(f"**{key.title()}:** {value}" for key, value in settings.items())))
        self.add_item(discord.ui.ActionRow(
            StatefulButton(label="Reset All", style=discord.ButtonStyle.danger, callback=self.reset_all),
        ))

    async def reset_all(self, interaction):
        async with self.batch():  # (1)!
            for key, value in DEFAULTS.items():
                await self.dispatch("SETTING_SET", {"guild": str(self.guild_id), "key": key, "value": value})  # (2)!
  1. Every action dispatched inside the block runs its reducer at once, and the panel hears about all of them together when the block ends.
  2. The action the panel's other controls send for one setting. Reset All reuses it four times.

Inside the block the state is current at every line: a dispatch can read what the one before it wrote. What waits is the announcement. When the outermost block ends, a single BATCH_COMPLETE action reaches every listener whose subscribed_actions or filter names any action in the batch, carrying them all in payload["actions"], and each listening view redraws once.

Reset All writing four settings Builds Requests to Discord
Without a batch 4 1 that answers the click, then 3 message edits
With self.batch() 1 1 that answers the click

With the batch, the panel shows the final settings after one request instead of four in a row.

Open the batch with the view's self.batch(). It names the view as the one acting, so the view redraws before the async with block returns and its edit can answer the click. store.batch() opens the same kind of batch with no acting view, and every listener redraws on a task of its own once the block has returned.

When to Batch

Batch when one click makes a change out of several actions: an existing action reused for each item, as Reset All does, or a mix of the library's helpers, such as a dispatch_scoped() and an update_session() that belong together. When one reducer can make the whole change, one action is simpler and needs no batch.

A batch does not speed up a slow reducer or a slow listener: it saves redraws, not work. To find where a dispatch spends its time, use the profiler.

What Joins a Batch

Every dispatch made inside the block joins it, through whichever helper made it:

async with self.batch():
    await self.dispatch("ROUND_STARTED")
    await self.update_session(seed=new_seed)  # (1)!
    async with self.batch():  # (2)!
        await self.dispatch_scoped({"last_move": None}, scope="user")
  1. update_session() and dispatch_scoped() dispatch through the store, so they join the batch too.
  2. A batch opened inside another joins the outer one: nothing is announced when it ends, and all three actions arrive in the outer batch's BATCH_COMPLETE.

  3. A batch belongs to the task that opened it. Two tasks batching at once announce separately, each in its own BATCH_COMPLETE.

  4. A task started inside the block joins the batch while the block is still open. Once the block has ended, its dispatches are announced one by one.
  5. A dispatch from another task while a batch is open is announced at once, with the state as it stands: the batch's actions so far are already in it. The batch's BATCH_COMPLETE follows when its block ends.
  6. A batch runs once. async with on the same batch a second time raises RuntimeError, so open a new one with self.batch().

When the Block Raises

A batch groups announcements, not changes: each action has changed the state by the time its dispatch() returns. When the block raises, the actions dispatched before the raise stay, they are announced together in one BATCH_COMPLETE, and the exception goes on to your code. With undo on, they form one undo step, so undo() takes them all back. Anything that must not survive the raise is for the block to put back itself.

The Library's Own Batches

send() registers a view in a batch of its own, so listeners hear one BATCH_COMPLETE holding its SESSION_CREATED and VIEW_CREATED. push() and pop() do the same for the screen they bring in, and the screen they leave is announced after it as one VIEW_DESTROYED. There is no need to wrap any of them in a batch.

Undo

With undo on, all the changes a view makes inside a batch are one undo step.

Code That Runs After an Action

Diagram: the order a dispatch runs in, for one action and inside a batch. One action: the reducer cast_vote changes the state, the view that dispatched redraws, the hooks run with that state, so log_vote logs 100 voted Pizza with 1 vote so far, and then dispatch() returns. Other views redraw on tasks of their own. Inside a batch, both reducers run, Kael's vote and then Mira's. When the block ends the view redraws once. The hooks for each VOTE_CAST run in order with the state the batch left, so both log 2 votes so far. Then the hooks for BATCH_COMPLETE run, and the async with block returns.

A hook runs after each action of the type it names, wherever the action came from. One that logs each vote cast in the poll further down this page:

import logging

from cascadeui import get_store, read_slot

log = logging.getLogger("polls")


def log_vote(action, state):  # (1)!
    total = len(read_slot(state, "votes", default={}))
    log.info(f"{action['payload']['user_id']} voted {action['payload']['choice']} (votes so far: {total})")


get_store().on("VOTE_CAST", log_vote)  # (2)!
  1. Called with the action and the state it left. A plain def or an async def.
  2. A custom action is named by its type. Remove the hook with get_store().off("VOTE_CAST", log_vote).

  3. The library's own actions also take a lower-case name: store.on("view_created", ...) hears VIEW_CREATED. The full list is in the reference. A custom action has no lower-case form, so store.on("vote_cast", ...) hears nothing. When VOTE_CAST already has a reducer, the store logs a WARNING asking whether you meant it.

  4. Hooks run before dispatch() returns, after the view that dispatched has redrawn. A slow hook holds up the click that dispatched, so hand slow work to a task of its own. Other views redraw on tasks of their own, before or after the hooks.
  5. A hook gets the state its action's subscribers got, even when another click has changed the state since.
  6. Inside a batch, the hooks run when the outermost block ends: each action's hooks in order, then those for BATCH_COMPLETE ("batch_complete"), all with the state the batch left.
  7. A hook that raises is logged at ERROR with its traceback, and the hooks after it still run.
  8. An action a middleware stops runs no hooks.
  9. A hook may dispatch. Registering the same function twice runs it twice, and each off() removes one. A hook in a cog belongs in cog_load(), with its off() in cog_unload(): a reloaded cog registers again.
  10. Treat the state as read-only. A write to it changes the store with no action, so no listener hears it and undo cannot take it back.
Runs Can change the action Hears
Middleware Around the reducer Yes, or stop it Every action
Subscriber After the reducer, filtered by type and selector No What it lists
Hook After the dispatching view's redraw No One action type

Values Derived From State

A computed value derives something from the state, and every view that reads it shares one result until the part of the state it reads changes. A poll's totals:

from cascadeui import cascade_reducer, computed, read_slot


@cascade_reducer("VOTE_CAST")
def cast_vote(action, state):
    votes = state["application"].setdefault("votes", {})
    votes[str(action["payload"]["user_id"])] = action["payload"]["choice"]
    return state


@computed(selector=lambda s: read_slot(s, "votes", default={}))  # (1)!
def vote_totals(votes):  # (2)!
    totals = {}
    for choice in votes.values():
        totals[choice] = totals.get(choice, 0) + 1
    return totals
  1. The selector picks the part of the state the value depends on. Read it from the state it is given.
  2. The function's name is the value's name: any view reads it as self.state_store.computed["vote_totals"].

How It Works

Table: what runs as votes come in, for the computed value vote_totals. Kael and Mira vote: nothing runs. A view reads vote_totals: the selector and the function run, giving Pizza 1, Tacos 1. Another view reads it: the selector runs, its selection is unchanged, and the stored result comes back, the same object. The theme changes, then a read: the selector runs and the stored result comes back. Ren votes, then a read: the selector and the function run, giving Pizza 2, Tacos 1.

  • Nothing runs until a read. A read runs the selector, and runs the function only when the selection differs from the one it last computed for, compared with ==. Otherwise it returns the stored result.
  • Votes cast with no one reading compute nothing. Changing another part of the state leaves the stored result as it is.
  • The function's result is stored only when it returns. One that raises leaves nothing stored, and the next read runs it again.
  • A read returns the value at once, so the function cannot be async: @computed on an async def raises TypeError.

Computed or state_selector()

@computed state_selector()
Belongs to The store, shared by every view One view
Answers A value derived from the state Whether this view should redraw
Read with store.computed["name"] Called by the store on each action the view hears
Stores One result per name One selection per view

Use @computed for a value several views show (totals, rankings, a leader). Use state_selector() to keep a view from redrawing for changes it does not show.

When It Recomputes

There is nothing to invalidate by hand. Each read compares the selection with the last one, so a value cannot go stale while the part of the state it reads stays the same. /cascadeui reset clears every stored result.

  • Every reader gets the same object. Treat it as read-only: a change to it shows in every later read.
  • Inside a reducer, store.computed reads the state as it was before the action. To derive from the state the reducer is building, call the function on it: @computed hands back the function unchanged, so vote_totals(read_slot(state, "votes", default={})) works there.
  • One function per name. A second function with the same name, in another cog for instance, raises ValueError naming both. The same function decorated again, as a reloaded cog does, replaces its registration.
  • store.computed is a read-only mapping: "vote_totals" in store.computed, store.computed.get(name), list(store.computed) for the names.

Full Example

v2_settings.py resets every setting inside self.batch(), behind a confirmation. v2_computed.py is a poll that keeps each server's votes apart and shows the totals and the current leader.