Link this shared state to a token. After linking, subsequent access to this shared state will affect the linked token's state, and cause changes to be propagated to all other clients linked to that token. Args: token: The token to link to (Cannot contain
(self, token: str)
| 209 | raise ReflexRuntimeError(msg) |
| 210 | |
| 211 | async def _link_to(self, token: str) -> Self: |
| 212 | """Link this shared state to a token. |
| 213 | |
| 214 | After linking, subsequent access to this shared state will affect the |
| 215 | linked token's state, and cause changes to be propagated to all other |
| 216 | clients linked to that token. |
| 217 | |
| 218 | Args: |
| 219 | token: The token to link to (Cannot contain underscore characters). |
| 220 | |
| 221 | Returns: |
| 222 | The newly linked state. |
| 223 | |
| 224 | Raises: |
| 225 | ReflexRuntimeError: If linking fails or token is invalid. |
| 226 | """ |
| 227 | if not token: |
| 228 | msg = "Cannot link shared state to empty token." |
| 229 | raise ReflexRuntimeError(msg) |
| 230 | if not isinstance(self, SharedState): |
| 231 | msg = "Can only link SharedState instances." |
| 232 | raise ReflexRuntimeError(msg) |
| 233 | if self._linked_to == token: |
| 234 | return self # already linked to this token |
| 235 | if self._linked_to and self._linked_to != token: |
| 236 | # Disassociate from previous linked token since unlink will not be called. |
| 237 | self._linked_from.discard(self.router.session.client_token) |
| 238 | # TODO: Change StateManager to accept token + class instead of combining them in a string. |
| 239 | if "_" in token: |
| 240 | msg = f"Invalid token {token} for linking state {self.get_full_name()}, cannot use underscore (_) in the token name." |
| 241 | raise ReflexRuntimeError(msg) |
| 242 | |
| 243 | # Associate substate with the given link token. |
| 244 | state_name = self.get_full_name() |
| 245 | if self._reflex_internal_links is None: |
| 246 | self._reflex_internal_links = {} |
| 247 | self._reflex_internal_links[state_name] = token |
| 248 | return await self._internal_patch_linked_state(token, full_delta=True) |
| 249 | |
| 250 | async def _unlink(self): |
| 251 | """Unlink this shared state from its linked token. |