I’m pretty new to this part of Phoenix, but I was able to figure out a very basic way to make the server send a message to a single room or a single user through the Phoenix API setup, without actually having to join the channel. In this case, a user will forward a message from one chat room to another chat room that they belong to (roomid
) without actually joining that room in their browser:
defmodule AppWeb.ChatController do
use Phoenix.Controller
def forward(conn, %{"room" => roomid, "userid" => _userid, "message" => _message} = payload) do
AppWeb.Endpoint.subscribe("room:#{roomid}")
AppWeb.Endpoint.broadcast("room:#{roomid}", "receiveMessage", payload)
json(conn, %{})
end
# catch-all error: sends back an empty JSON array for all requests that don't have required params
def forward(conn, %{}) do
IO.inspect("Invalid parameters")
json(conn, %{})
end
end
From what I understand, AppWeb.Endpoint.subscribe / AppWeb.Endpoint.broadcast
is actually using PubSub in the background? And the script is required to subscribe to that room before any message/notification can be sent to it?
In the function above, the app subscribes to that room and then sends the message. It only needs to be done once. So does it unsubscribe automatically after the function ends? I’m concerned that the server may accumulate a huge list of subscriptions in the background, when all it needs to do is fire off quick, one-time messages when needed. Or am I not using PubSub correctly in the way I’m intending?
How to send sitewide notifications to list of users as well?
Let’s say this room has 20 users - some are in the room topic, such as room:159
, some are offline, and some are browsing other pages on the website. Each individual user has already joined their own user topic, such as user:1
, user:244
, user:6234
, etc.
The next step in my journey is that in addition to sending the forwarded message to that room, I also want to send a notification to all users that might be somewhere else in the website (not actually in the room), and put a note in their notification bell that their group chat received a new message.
Is there some way for PubSub to quickly subscribe to a whole list of those user topics and send a notification to each of them? For example, how could I do something like this?:
userList = ["user:1", "user:244", "user6234", ...]
AppWeb.Endpoint.subscribe(userList)
AppWeb.Endpoint.broadcast(userList, "receiveNotification", payload)
Or is there some other method designed for this?