Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```elixir
- defmodule MyApp.PubSub do
- @moduledoc """
- Centralized module for handling pub/sub broadcasts in MyApp.
- """
- # ---------------------
- # User broadcasts
- # ---------------------
- # User topics
- defp user_topic(user_id), do: "user:#{user_id}"
- # User events
- defmodule Events.User do
- def inventory_update, do: :inventory_update
- def equipment_update, do: :equipment_update
- def resources_update, do: :resources_update
- def balance_update, do: :balance_update
- def strongbox_update, do: :strongbox_update
- def items_salvaged, do: :items_salvaged
- def unread_message_count, do: :unread_message_count
- end
- def subscribe_to_user(user_id) do
- Phoenix.PubSub.subscribe(Shopkeep.PubSub, user_topic(user_id))
- end
- def update_user_inventory(user_id, inventory) do
- broadcast_to_user(user_id, {Events.User.inventory_update(), inventory})
- end
- end
- ```
- ...
- ```elixir
- # home_live.ex
- defmodule MyAppWeb.HomeLive do
- # ...
- # PubSub.subscribe_to_user(user.id) happens above
- # trying to avoid issues with typos in atom names - (intentional typo ":inventoryy")
- # publisher sends events, is never handled properly
- # may throw runtime error but it's reverse "no handler for :inventory in home_live"
- def handle_info({:inventoryy, inventory}, socket) do
- socket =
- socket
- |> assign(:inventory, inventory)
- |> maybe_update_equipped_stats(:inventory)
- {:noreply, socket}
- end
- # Below complains - cannot invoke remote function MyApp.PubSub.Events.User.inventory_update/0 inside a matchElixir
- def handle_info({Events.User.inventory_update(), inventory}, socket) do
- socket =
- socket
- |> assign(:inventory, inventory)
- |> maybe_update_equipped_stats(:inventory)
- {:noreply, socket}
- end
- # below works, but is verbose - I'm OK with this for now but feels like a code/design smell
- @inventory_update_event Events.User.inventory_update()
- def handle_info({@inventory_update_event, inventory}, socket) do
- socket =
- socket
- |> assign(:inventory, inventory)
- |> maybe_update_equipped_stats(:inventory)
- {:noreply, socket}
- end
- end
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement