Unsubscribe from PubSub upon exiting Phoenix Live View

I was wondering how I could unsubscribe from a PubSub topic whenever a LiveView is exited e.g. by redirecting to a different page. Subscribing to a topic upon mounting is easy:

def mount(%{"id" => id}, _session, socket) do
  if connected?(socket), do: Endpoint.subscribe("my-topic:#{id}")
  {:ok, socket}
end

However, I am unsure what happens when I destroy the LiveView process by e.g. redirecting to a different page. Is the LiveView process unsubscribed automatically? If not, is there an unmount function in which I could unsubscribe before the LiveView process is destroyed?

4 Likes

Yes. The subscription is tied to the life of the process, and when you go to a different page the live view process is terminated. The subscription is automatically cleaned up as a consequence. Cool eh?

8 Likes

Pfeuw! Pretty cool indeed :slight_smile: A hurray to OTP! Thanks for the info!

1 Like

Hi,
is the same behaviour when I close website by closing web browser (not going to different page) ?

Since closing your browser would sever your websocket connection just as navigating to a different page, I would expect this to terminate the LiveView Process as well which would unsubscribe the process from the topic as mentioned earlier. So, I believe: Yes.