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?

13 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.

I did a bit of digging and learned that Phoenix.PubSub uses Registry.register and Registry.dispatch under-the-hood for message passing to subscribed processes.

Documentations states "For example, if a process crashes, its keys are automatically removed from the registry but the change may not propagate immediately.

I also tested this by calling Phoenix.PubSub.subscribe in two processes, killing one, then checking the registry and finding that it indeed only had one process registered.

4 Likes