Skip to content

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.

Animation: Kael's counter in server 22 shows 5. Three actions arrive in turn. GREETING_SET is not in the view's subscribed_actions, so nothing runs. COUNT_ADDED for server 22 makes the count 6: state_selector() returns 6, on_state_changed() runs, and the panel redraws to show 6. COUNT_ADDED for server 33 is listed too, but state_selector() still returns 6, so nothing runs.

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)
  1. The actions the view hears. Every COUNT_ADDED, from any server, reaches every CounterView.
  2. 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:

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 naming VIEW_CREATED or SESSION_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}!")
  1. check runs after every COUNT_ADDED, from any server. Leave out action_filter= to hear every action.
  2. A subscriber lasts until it is removed. Subscribing again under the same id replaces it.
  3. Called with the store's state just after the action, and the action. A plain def works too.

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

  5. state is the state just after this action, even when later actions have landed by the time the callback runs.
  6. selector= takes its first value when you subscribe, so the callback runs only once the selection changes from it. A view's state_selector() takes none, which is why a view's first action redraws it (see Selectors).
  7. An UNDO or REDO reaches 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 one BATCH_COMPLETE holding all of them, when the filter names any of their types.
  8. subscribe() raises TypeError for a callback that cannot take (state, action) or a selector that cannot take (state), and ValueError for a view's id: a view subscribes itself, and unsubscribes when it closes, by exit() or a timeout.
  9. 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.

Timeline: on_state_changed() awaits a 1-second database call. The first COUNT_ADDED starts a run that reads 5. Three more arrive while it runs and start no run of their own. When the first run ends, one more run starts and reads 8.

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}**"))
  1. 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).
  2. Reads state["application"]["stats"][key]["wins"] from the store each time self.wins is read, or 0 when any part is missing. key is called with the view.
  3. The same value, read from the state the selector is given.

The application part of the state: the counts slot, and a stats slot holding "42" with wins: 3. access_slot(state, "stats", "42") returns the "42" entry to change. read_slot(state, "stats", "42", "wins", default=0) and the slot_property wins both read 3. read_slot(state, "stats", "42", "wins", 0), with the default passed by position, looks for a key 0 under the 3 and returns None.

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, raises TypeError naming the slot. So does a key of None, such as a guild_id read in a DM, before anything is written.
  • A slot_property whose key cannot take the view raises TypeError where it is declared.
  • Assigning a slot_property (view.wins = 5) raises AttributeError. Change the value in a reducer.
  • read_slot()'s default is keyword-only. Passed by position it is one more key in the path, so read_slot(state, "stats", "42", "wins", 0) looks for a key 0 under the wins and returns None, 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:

class StatsView(StatefulLayoutView):
    persistent_slots = ("stats",)

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:

Animation: before a restart, the stats slot is keyed by the number 42, and read_slot(state, "stats", 42, "wins") reads 3. The save logs an ERROR naming the key 42. After the restart the slot comes back keyed by the string "42": read_slot with 42 finds nothing and returns the default, 0, while read_slot with "42" reads 3.

Key a saved slot by str(user_id), as record_win above does.