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¶
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)!
- Every action dispatched inside the block runs its reducer at once, and the panel hears about all of them together when the block ends.
- 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")
update_session()anddispatch_scoped()dispatch through the store, so they join the batch too.-
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. -
A batch belongs to the task that opened it. Two tasks batching at once announce separately, each in its own
BATCH_COMPLETE. - 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.
- 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_COMPLETEfollows when its block ends. - A batch runs once.
async withon the same batch a second time raisesRuntimeError, so open a new one withself.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¶
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)!
- Called with the action and the state it left. A plain
defor anasync def. -
A custom action is named by its type. Remove the hook with
get_store().off("VOTE_CAST", log_vote). -
The library's own actions also take a lower-case name:
store.on("view_created", ...)hearsVIEW_CREATED. The full list is in the reference. A custom action has no lower-case form, sostore.on("vote_cast", ...)hears nothing. WhenVOTE_CASTalready has a reducer, the store logs a WARNING asking whether you meant it. - 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. - A hook gets the state its action's subscribers got, even when another click has changed the state since.
- 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. - A hook that raises is logged at ERROR with its traceback, and the hooks after it still run.
- An action a middleware stops runs no hooks.
- A hook may dispatch. Registering the same function twice runs it twice, and each
off()removes one. A hook in a cog belongs incog_load(), with itsoff()incog_unload(): a reloaded cog registers again. - 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
- The selector picks the part of the state the value depends on. Read it from the state it is given.
- The function's name is the value's name: any view reads it as
self.state_store.computed["vote_totals"].
How It Works¶
- 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:
@computedon anasync defraisesTypeError.
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.computedreads the state as it was before the action. To derive from the state the reducer is building, call the function on it:@computedhands back the function unchanged, sovote_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
ValueErrornaming both. The same function decorated again, as a reloaded cog does, replaces its registration. store.computedis 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.
Related¶
- Store, Actions, and Reducers: what a dispatch does
- Subscribers and Slots: which views hear an action
- Undo and Redo: taking a batch back as one step
- Middleware: code that runs around every reducer