Alex Antonov
Alex Antonov

Reputation: 15156

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?

Upvotes: 5

Views: 1790

Answers (1)

Patrick Oscity
Patrick Oscity

Reputation: 54684

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

Upvotes: 9

Related Questions