julngomz

julngomz

Phoenix LiveView, WebSockets, PubSub and Message Broadcasting

Hello All,

I need some clarifications on using WebSockets and Pub/Sub in/with Phoenix LiveView.

I have the example working where I can create, store, and delete the message and reflect them on the message feed. All I need to do now is reflect them to other users in the chat.

I am currently using Phoenix.Socket.Transport but later down the road I’ll just probably implement that using Cowboy via the behaviour :cowboy_websocket.

I have the ChatSocket implemented and defined in the Endpoint as follows.

In endpoint.ex,

 socket "/chat/:user_id/:room_id/", AppWeb.ChatSocket, websocket: true, longpoll: true

I can do some subscribing and publishing via the user_id and room_id.

On every room change, LiveView updates the websocket URL and the user_id is populated with the current authenticated users id and the selected room id,

ws://localhost:4000/chat/#{@current_user.id}/#{@active_room.id}/websocket

that in turn is passed to a JavaScript Hook (phx-hook={Chat}) via the data-ws-url attribute that implements the WebSocket and other niceties such as scrolling down/up? to the first message, etc.

I have the ChatSocket receiving a heartbeat from clients but now the confusion arises.

I understand the theory behind WebSockets and how they work I can send heartbeats to the ChatSocket as you can see in the following image:

I can also send messages to the WebSocket:

So essentially what I’m doing is the following:

  • A new message is created
  • It is saved in the database
  • the stream is updated and rendered
  • the message is then sent to the websocket
  • (potentially) pub/sub then broadcasts them to subscribed members

Note: All I care about for now is basic message storing and broadcasting there is quite a bit of edge cases I am not handling at the moment.

So the question I have is where do I plop in the Phoenix PubSub?

Since this is a SPA app and I retrieve all user information such as chatrooms along with messages, members, and member profiles. I was thinking about subscribing when I retrieve information and accessing it in the ChatSocket that way I can get new message information and display a badge with the latest message.

Thank you for taking your time with my post. Any help/clarifications is appreciated.

Marked As Solved

codeanpeace

codeanpeace

I’d suggest looking into Phoenix.Channels which uses Phoenix.PubSub under the hood.

At a high level, you’ll want to subscribe to the chatroom topic in mount callback, publish/broadcast the message in handle_event callback for new messages from the client, and finally handling those messages published/broadcasted from other clients in handle_info callback. For a minimal working example, take a look at Step 4 — Subscribe & Consume Messages in Build Real-time Chat With Phoenix and LiveView in Fewer Than 50 Lines of Code.

And if you want to use Phoenix.PubSub directly, here’s a helpful repo that walks through the process in its readme: GitHub - dwyl/phoenix-liveview-chat-example: 💬 Step-by-step tutorial creates a Chat App using Phoenix LiveView including Presence, Authentication and Style with Tailwind CSS · GitHub.

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement