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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With