phoenix-pubsub-patterns
Installation
SKILL.md
Phoenix PubSub Patterns
RULES — Follow these with no exceptions
- Always guard subscriptions with
if connected?(socket)— the disconnected render runs in a separate short-lived process; subscribing there is wasted work, not a duplicate (LiveView mounts twice: once static, once connected) - Broadcast from contexts, not LiveViews — keeps real-time logic in the business layer; LiveViews only subscribe and react
- Use consistent topic naming —
"resource:id"for specific resources,"resource:action"for collection-wide events - Handle PubSub messages in
handle_info/2— never inhandle_event/3; PubSub messages are process messages, not client events - Prefer
update/3when the new value derives from the old —update(socket, :posts, &[post | &1])reads better than reaching intosocket.assignsmanually. Both are equivalent; this is style, not safety. - Test PubSub by calling context functions and asserting LiveView updates — don't test
PubSub.broadcastdirectly; test the full cycle
Subscription Pattern
Subscribe in mount/3 only when connected. The static render doesn't need real-time updates.