Get Notified When An User Leaves A Phoenix Channel
This post is based on the stackoverflow answer by Chris McCord to my question on this topic (see here).
I’m working on a project where I wanted to trigger a function when an user leaves a Phoenix channel due to closing the app, losing network connection and so on (basically every “leaving event” where the app is not able to notify the server).
The answer is using a GenServer to watch the established connection and trap the exit.
lib/my_app.ex
web/channels/user_socket.ex
web/channels/room_channel.ex
lib/my_app/channel_watcher.ex
Conclusion
This system works very well for me in production. And compared to Faye with which I worked in the past, I begin to see the true power of Elixir/Erlang. It’s just a blast!