Advertisement
Guest User

Untitled

a guest
Jan 24th, 2025
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1.  
  2. ```elixir
  3. defmodule MyApp.PubSub do
  4. @moduledoc """
  5. Centralized module for handling pub/sub broadcasts in MyApp.
  6. """
  7.  
  8. # ---------------------
  9. # User broadcasts
  10. # ---------------------
  11.  
  12. # User topics
  13. defp user_topic(user_id), do: "user:#{user_id}"
  14.  
  15. # User events
  16. defmodule Events.User do
  17. def inventory_update, do: :inventory_update
  18. def equipment_update, do: :equipment_update
  19. def resources_update, do: :resources_update
  20. def balance_update, do: :balance_update
  21. def strongbox_update, do: :strongbox_update
  22. def items_salvaged, do: :items_salvaged
  23. def unread_message_count, do: :unread_message_count
  24. end
  25.  
  26. def subscribe_to_user(user_id) do
  27. Phoenix.PubSub.subscribe(Shopkeep.PubSub, user_topic(user_id))
  28. end
  29.  
  30. def update_user_inventory(user_id, inventory) do
  31. broadcast_to_user(user_id, {Events.User.inventory_update(), inventory})
  32. end
  33. end
  34. ```
  35.  
  36. ...
  37.  
  38. ```elixir
  39. # home_live.ex
  40.  
  41. defmodule MyAppWeb.HomeLive do
  42. # ...
  43. # PubSub.subscribe_to_user(user.id) happens above
  44.  
  45. # trying to avoid issues with typos in atom names - (intentional typo ":inventoryy")
  46. # publisher sends events, is never handled properly
  47. # may throw runtime error but it's reverse "no handler for :inventory in home_live"
  48. def handle_info({:inventoryy, inventory}, socket) do
  49. socket =
  50. socket
  51. |> assign(:inventory, inventory)
  52. |> maybe_update_equipped_stats(:inventory)
  53.  
  54. {:noreply, socket}
  55. end
  56.  
  57. # Below complains - cannot invoke remote function MyApp.PubSub.Events.User.inventory_update/0 inside a matchElixir
  58. def handle_info({Events.User.inventory_update(), inventory}, socket) do
  59. socket =
  60. socket
  61. |> assign(:inventory, inventory)
  62. |> maybe_update_equipped_stats(:inventory)
  63.  
  64. {:noreply, socket}
  65. end
  66.  
  67. # below works, but is verbose - I'm OK with this for now but feels like a code/design smell
  68. @inventory_update_event Events.User.inventory_update()
  69. def handle_info({@inventory_update_event, inventory}, socket) do
  70. socket =
  71. socket
  72. |> assign(:inventory, inventory)
  73. |> maybe_update_equipped_stats(:inventory)
  74.  
  75. {:noreply, socket}
  76. end
  77. end
  78. ```
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement