Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I know amount of connections to channel in phoenix?

I have a pretty simple chat application, and I want to implement some specific actions when user exits from the page (that is, terminate/2 connection). But I want to implement this action if there is nobody else connected to this topic.

How could I do that?

like image 794
asiniy Avatar asked Feb 05 '23 09:02

asiniy


1 Answers

This may sound like a trivial problem but it is not. You need to deal with connectivity issues and so on. Luckily this is a common enough problem that there's a standard solution for it, which comes bundled with Phoenix - Phoenix.Presence. It will allow you to reliably track online users for a given topic.

Follow the steps here to set up Presence: https://hexdocs.pm/phoenix/Phoenix.Presence.html

Then in your terminate/2 callback, you can check if all users left the topic with

if Presence.list(socket) |> Enum.empty? do
  # do something
end
like image 178
Patrick Oscity Avatar answered Feb 11 '23 16:02

Patrick Oscity