jtormey

jtormey

Adding a handle_info callback to LiveComponents

Lately I’ve been thinking about how to organize components as a LiveView application grows. One of the pain points I’ve found (for myself and beginners) is communicating over PubSub with LiveComponents. The only way to do so is through the parent LiveView, which works well but introduces boilerplate and some indirection, as the LiveView is required to maintain the PubSub subscriptions, and communicate state changes via component assigns or send_update/2.

It would be nice if LiveComponents could implement a handle_info/2 callback, and had a way to manage their own PubSub subscriptions. Well, I was able to implement just that. This is how the “connected” component itself looks:

defmodule CounterComponent do
  use AppWeb, :connected_component

  def render(assigns) do
    ~H"""
    <div {@connected_attrs}>{@count}</div>
    """
  end

  def on_mount(socket) do
    process_setup = fn ->
      Phoenix.PubSub.subscribe(App.PubSub, "inc_channel")
    end

    {:ok, assign(socket, :count, 0), process_setup}
  end

  def handle_info(:inc, socket) do
    {:noreply, update(socket, :count, &(&1 + 1))}
  end
end

I’ve called it “connected” because the component has its own process, which is connected to it via the parent LiveView process. In the on_mount/1 callback, the component returns an anonymous function which is called in a new process and creates any interprocess connections needed by the component (generally, PubSub subscriptions).

In this example, the component receives :inc messages via inc_channel, which when received increments the :count assign on the component. The advantage of this is that the LiveComponent is now fully encapsulated, including its interactions with PubSub.

You can find a complete example and demo video here: GitHub - jtormey/connected_component_demo: Phoenix LiveView project demoing the ConnectedComponent concept · GitHub

The implementation itself is here (not extensively tested, there may be bugs).

Using these components is transparent to the parent LiveView and even allows for deeply nested components to have their own handle_info/2 callbacks. It just requires an on_mount/1 handler to be called in the parent LiveView, which can be applied for all LiveViews globally by calling it in the live_view/1 macro in your web module (you can see how this works in the demo application).

There is a slight performance cost: an additional process for each component that uses this pattern, and each message that is received is copied one more time than would normally be necessary. Though I think these can be justified.

I’m curious if anyone would find this useful in their own applications. Personally I like the convenience and the API, and wonder if something like this might be a worthwhile addition to LiveView itself.

Most Liked

gushonorato

gushonorato

I’m not sure if I agree with that statement because the LiveComponent state will also need to be stored, though not in a lightweight process, but in the parent LiveView. However, I don’t think that’s the main point of the discussion.

I understand that the initial problem you’re trying to solve is the communication between LiveComponents and PubSub. Since the discussion has shifted towards efficiency, I believe it would be beneficial to avoid creating a separate process to accommodate this feature. Instead, a “message broker” within the LiveView itself could handle this task, eliminating the need to spawn additional processes. This approach is more efficient and avoids introducing extra complexity to the LiveComponents.

jtormey

jtormey

I agree, it would be best if the extra process wasn’t necessary. However I wasn’t able to come up with a solution for automatically brokering messages in a single process, there are too many complications and you end up back where we started with manual message routing.

The extra process removes this complexity entirely, when it receives a message you know exactly the component its meant for, then it’s tagged as such and relayed to it. And this is opt-in, you wouldn’t use this for the majority of your components.

If you have specific ideas on implementing a single-process message broker I would love to hear them!

olivermt

olivermt

A major difference is that passing props to a nested liveview and updating it on-page (outside of messages) is much more clunky.

That said I am not convinced the upside is bigger than the added downside/complexity.

Where Next?

Popular in Discussions Top

mikl
I wanted to capitalize a string, and tried using String.capitalize(). That generally works well, until you try to capitalize a word like...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
nunobernardes99
Hi there Elixir friends :vulcan_salute: In a recent task I was on, I needed to check in two dates which of them is the maximum and which...
New
AlexMcConnell
The reason that Rails is as popular as it is is because it’s very easy for relatively inexperienced developers to get a lot of work done....
588 19675 166
New
mbenatti
Following https://github.com/tbrand/which_is_the_fastest |&gt; https://raw.githubusercontent.com/tbrand/which_is_the_fastest/master/imgs...
New
jer
I’ve been using umbrellas for a while, and generally started off (on greenfield projects at least) by isolating subapps based on clearly ...
New
hazardfn
I suppose this question is effectively hackney vs. ibrowse but we are at a point in our project where we have to make a choice between th...
New
acrolink
How does the two languages compare when it comes to server side application development? Any experiences or ideas? Thank you.
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

Other popular topics Top

ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52774 488
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement