mortenlund

mortenlund

LiveView - Live Component - unmount callback

Hi!
I would like to suggest a new callback in the lifecycle of the Live Component which is unmount.

Sometimes it is nice to be able to cleanup subscriptions and such when the component is removed from the page.

An example is a “chat” component I made that subscribes to PubSub.
The component is used in a page with tabs and is only present in one of the tabs.
Being able to unsubscribe from the PubSub in the same way the subscription was made in mount would be very nice.

First Post!

D4no0

D4no0

I think you should be able to use this terminate callback, even though it’s not guaranteed that it will get called (read why in the docs).

The official way to do this is by monitoring the process: Process — Elixir v1.20.2

Most Liked

LostKobrakai

LostKobrakai

How would you decide if a message received for being subscribed to pubsub is meant to be forwarded to the live component? Those messages are in arbitrary shape and don’t include any hint if the source for the subscription might be a child live component or the live view itself. It could even be that both are subscribed to the same pubsub.

LostKobrakai

LostKobrakai

Tbh I think the issue here is that you use a LiveComponent to subscribe to PubSub in the first place. Given LiveComponents are indeed not processes you’re essentially leaking a subscription onto the parent LiveView as a sideeffect, which then materializes by the fact that you cannot clean that up anymore. I agree that this is a limitation to what a LiveComponent can encapsulate, but imo the solution isn’t an unmount callback. Even with that there would still be no handle_info callback as well, so you’re still dependant on the parent LV.

mortenlund

mortenlund

I very much agree on this!

I have another suggestion to allow PubSub to send events directly to the LiveComponent since this is the same way LiveComponent allready gets its message when using send_update.
Then the LiveComponent could be able to use PubSub without involving the parent LiveView.

This could then call update/2 in the same way send_update allready does this :slight_smile:

The way I solve the handle_info in the parent today is to use Phoenix.LiveView.attach_hook/4 function and then use send_update to forward it to the component :slight_smile:
I attach the hook by defining a hook/1 function in my component that is called from the LiveView.mount function :slight_smile:

Last Post!

mortenlund

mortenlund

Well, they can with some slight tricks :slight_smile: :slight_smile:

I currently have a special module like this that handles the subscription and acts as a special dispatcher.
This does not rely on the parent LiveView and the subscription will be cleaned up when the parent LiveView process dies as normal PubSub subscriptions :slight_smile:

defmodule MyLiveComponent.PubSub do
  @moduledoc false

  def subscribe(%Phoenix.LiveView.Socket{assigns: %{myself: myself} = socket, pubsub, topic) do
    if Phoenix.LiveView.connected?(socket) do
      Phoenix.PubSub.subscribe(pubsub, topic, metadata: %{pid: self(), cid: myself})
      socket
    else
      socket
    end
  end

  def subscribe(%Phoenix.LiveView.Socket{} = socket, pubsub, topic) do
    Phoenix.PubSub.subscribe(pubsub, topic)
    socket
  end

  def unsubscribe(pubsub, topic) do
    Phoenix.PubSub.unsubscribe(pubsub, topic)
  end

  def broadcast(pubsub, topic, message) do
    Phoenix.PubSub.broadcast(
      pubsub,
      topic,
      message,
      __MODULE__
    )
  end

  def broadcast_from(pubsub, pid, topic, message) do
    Phoenix.PubSub.broadcast_from(
      pubsub,
      pid,
      topic,
      message,
      __MODULE__
    )
  end

  def local_broadcast(pubsub, topic, message) do
    Phoenix.PubSub.local_broadcast(
      pubsub,
      topic,
      message,
      __MODULE__
    )
  end

  def dispatch(entries, _dispatch_identificator, message) do
    entries
    |> Enum.each(fn
      {_pid, %{cid: cid, pid: pid}} ->
        Phoenix.LiveView.send_update(pid, cid, source: :pubsub, message: message)

      {pid, _} ->
        send(pid, message)
    end)

    :ok
  end
end

And a live component can be something like this:

defmodule MyComponent do
  use MyWeb, :live_component
  import MyWeb.CoreComponents

  @impl true
  def render(assigns) do
   ~H"""
     <%= @message %>
    <.button phx-event="send">Send</.button>
   """
  end

  @impl true
  def update(%{source: :pubsub, message: message}, socket) do
    socket
    |> assign(:message, message)
  end

  @impl true
  def mount(socket) do
    updated_socket = socket
    |> assign(:message, "No message")
    |> MyLiveComponent.PubSub.subscribe(MyPubSub, "topic")

    {:ok, updated_socket}
  end

  @impl true
  def handle_event("send", _params, socket) do
    MyLiveComponent.PubSub.broadcast(MyPubSub, "topic", "We got a message!")
    {noreply, socket}
  end

Where Next?

Trending in Proposals: Ideas Top

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New
webofbits
Squid Mesh is an open source workflow automation runtime for Elixir applications. It is aimed at Phoenix and OTP apps that want to defin...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
kip
In 2021 I started a new library called Tempo with the objective of modelling time as a set of intervals - not as instants. In 2022 I gave...
New

We're in Beta

About us Mission Statement