Subscribers and Slots¶
A view hears the actions it lists, from any panel in any server, and redraws only when the values it shows have
changed. This page covers choosing both, the same notifications for code that is not a view, and slots, the named
places under state["application"] where reducers keep their data.
What a View Hears¶
The counter on Store, Actions, and Reducers declares both:
from cascadeui import StatefulLayoutView, read_slot
class CounterView(StatefulLayoutView):
subscribed_actions = {"COUNT_ADDED"} # (1)!
def state_selector(self, state): # (2)!
return read_slot(state, "counts", str(self.guild_id), default=0)
- The actions the view hears. Every
COUNT_ADDED, from any server, reaches everyCounterView. - What the panel shows: this server's count. The view redraws only when it changes.
Kael's counter is in server 22 and shows 5. Three actions arrive:
GREETING_SETis not insubscribed_actions, so nothing runs.COUNT_ADDEDfor server 22 makes it 6.state_selector()returns 6, so the view'son_state_changed()runs, and by default it callsbuild_ui()andrefresh().COUNT_ADDEDfor server 33 is heard too, butstate_selector()still returns 6, so nothing runs.
subscribed_actions is empty by default, so a view hears only an undo or redo of its own history, and a type it
lists brings the undo of a step holding that type too (see Undo and Redo). With subscribed_actions = None a view hears every action, the library's own
included: every other view's send and close runs its on_state_changed() too.
set_class_attribute() changes the list for one view.
A view hears only the exact types it lists. A listed type that no reducer or hook handles and nothing has dispatched, but that is close to one that is, logs a WARNING once, when the first view listing it is built:
CounterView.subscribed_actions names 'COUNT_ADED', which no reducer or hook handles and nothing has dispatched. Did you mean 'COUNT_ADDED'? A listener hears only the exact type it names.
A type that resembles nothing known passes without a word, since code that has not run yet may dispatch it.
Selectors¶
After each action a view hears, the library calls state_selector() with the store's state and compares what it
returns with what it returned last time, using ==. When the two are equal, nothing runs. Return what the panel
shows and nothing more: a change to anything else in the return value redraws the panel for nothing.
- With no
state_selector(), every action the view lists redraws it. - The first action a view hears runs
on_state_changed()even when nothing changed, and a redraw that comes out the same as the panel on screen sends no edit. A view that hears its own send's actions (subscribed_actions = None, or a list namingVIEW_CREATEDorSESSION_CREATED) hears them during the send, so after it only a changed selection redraws. - The view's theme is compared along with the selection, so a view whose
get_theme()follows the state redraws when its theme changes, at the next action it hears.
Read the state from the argument. A view has no self.state: a selector that reads it raises AttributeError,
which the store logs once as a WARNING, and until the selector stops raising, every action the view lists
redraws it.
Code That Is Not a View¶
store.subscribe() gives any
code the same notifications. A cog that announces every hundredth count in a server:
from discord.ext import commands
from cascadeui import get_store, read_slot
class Milestones(commands.Cog):
def __init__(self, bot):
self.bot = bot
get_store().subscribe("milestones", self.check, action_filter={"COUNT_ADDED"}) # (1)!
def cog_unload(self):
get_store().unsubscribe("milestones") # (2)!
async def check(self, state, action): # (3)!
guild_id = action["payload"]["guild_id"]
count = read_slot(state, "counts", str(guild_id), default=0)
guild = self.bot.get_guild(guild_id)
if count % 100 == 0 and guild and guild.system_channel:
await guild.system_channel.send(f"This server just reached {count}!")
checkruns after everyCOUNT_ADDED, from any server. Leave outaction_filter=to hear every action.- A subscriber lasts until it is removed. Subscribing again under the same id replaces it.
-
Called with the store's state just after the action, and the action. A plain
defworks too. -
The callback runs as a task of its own, so a slow one holds up no click. The task can start before
dispatch()returns, wherever the dispatch waits (the clicked view's own redraw, a hook that awaits). One that raises is logged at ERROR with its traceback, and the others still run. stateis the state just after this action, even when later actions have landed by the time the callback runs.selector=takes its first value when you subscribe, so the callback runs only once the selection changes from it. A view'sstate_selector()takes none, which is why a view's first action redraws it (see Selectors).- An
UNDOorREDOreaches a subscriber whose filter names a type of an action the step takes back (see Who Redraws After an Undo). Actions dispatched inside a batch arrive as oneBATCH_COMPLETEholding all of them, when the filter names any of their types. subscribe()raisesTypeErrorfor a callback that cannot take(state, action)or a selector that cannot take(state), andValueErrorfor a view's id: a view subscribes itself, and unsubscribes when it closes, byexit()or a timeout.- A filter type that looks like a misspelling logs the WARNING a view's list does.
When Changes Arrive Together¶
A view redraws one change at a time. Actions it hears while on_state_changed() runs do not each start a redraw:
they fold into one more run once it ends, which is passed the store's state as it is then. A redraw that waits on
a database call falls behind by one run at most, and two people clicking at once never build the panel at the
same time.
Four COUNT_ADDED gave two runs here, so count from the state, never from the number of runs.
A click that lands while the panel is being rebuilt still reaches the view: the buttons on screen go on working until the new edit lands.
Application Slots¶
A slot is a named place under state["application"] where reducers keep their data: the counter's counts sit in
the "counts" slot. Give each feature a name of its own, since code that uses the same name shares the slot. Three
helpers read and write slots:
| Helper | Use it in | What it does |
|---|---|---|
access_slot(state, name, key) |
Reducers and seed_initial_state() |
Returns application[name][key] to change in place, creating the slot and the entry as empty dicts when they are missing. With no key, it returns the slot. |
read_slot(state, name, *path, default=None) |
Selectors, @computed functions, build_ui() |
Walks application[name] along the path and returns what it finds, or default when any step is missing. It changes nothing. |
slot_property(name, slot=, key=, default=) |
A view's class body | A read-only attribute that reads application[slot][key(view)][name] from the store each time it is read. |
Per-player wins, kept in a "stats" slot:
from cascadeui import (
StatefulLayoutView, access_slot, card, cascade_reducer, read_slot, slot_property,
)
@cascade_reducer("MATCH_WON")
def record_win(action, state):
player = access_slot(state, "stats", str(action["payload"]["user_id"])) # (1)!
player["wins"] = player.get("wins", 0) + 1
return state
class StatsView(StatefulLayoutView):
subscribed_actions = {"MATCH_WON"}
wins = slot_property("wins", slot="stats", key=lambda view: str(view.user_id), default=0) # (2)!
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.build_ui()
def state_selector(self, state):
return read_slot(state, "stats", str(self.user_id), "wins", default=0) # (3)!
def build_ui(self):
self.clear_items()
self.add_item(card(f"Wins: **{self.wins}**"))
state["application"]["stats"]["<user id>"], created as{}the first time. The reducer's state is its own copy, so changing this entry changes the state the store keeps. The key is a string so the slot can be saved (below).- Reads
state["application"]["stats"][key]["wins"]from the store each timeself.winsis read, or 0 when any part is missing.keyis called with the view. - The same value, read from the state the selector is given.
access_slot(..., default_factory=list) creates a missing entry with what the function returns in place of
{}. For a path deeper than slot, key, and field, write a property that calls read_slot():
class PlayerCard(StatefulLayoutView):
@property
def combat_wins(self):
return read_slot(self.state_store.state, "stats", str(self.user_id), "combat", "wins", default=0)
Three mistakes the helpers catch, and one they cannot:
access_slot()with a key, on a slot that holds something other than a dict, raisesTypeErrornaming the slot. So does a key ofNone, such as aguild_idread in a DM, before anything is written.- A
slot_propertywhosekeycannot take the view raisesTypeErrorwhere it is declared. - Assigning a
slot_property(view.wins = 5) raisesAttributeError. Change the value in a reducer. read_slot()'sdefaultis keyword-only. Passed by position it is one more key in the path, soread_slot(state, "stats", "42", "wins", 0)looks for a key0under the wins and returnsNone, with nothing raised.
Slots That Survive a Restart¶
With persistence set up, a slot can be saved and loaded back after a restart. Mark it in either of two places:
or access_slot(state, "stats", key, persistent=True). Either marks the name for good, so every later write to
the slot is saved, wherever it comes from. Saving Data covers a
third way and how long a saved slot is kept.
A saved slot's keys must be strings. JSON keeps every key as a string, so a slot keyed by the number 42 comes back
keyed by "42", and a lookup by 42 then finds nothing. The save logs an ERROR naming the key, and writes the slot
anyway, since refusing it would lose every other entry in it too:
Key a saved slot by str(user_id), as record_win above does.
Related¶
- Store, Actions, and Reducers: dispatching actions and writing the reducers that fill slots
- Scoped State: data kept per person or per server without a reducer
- Batching, Hooks, and Computed Values: several dispatches as one, and values derived from the state
- Saving Data: saved slots, how long they are kept, and pruning them