longnightElixir

longnightElixir

Are there elegant ways to sub/unsub when user navigated between routers in same liveview?

Hi, I have some usage scenario to ask:

Users navigate between ` /product/product_a_id ` and ` /product/product_b_id` , and more ;
these routers are in the same liveview;

I have background running jobs will send events (and data) to users who is staying on specified product detail page; this may approach by using Pubsub or Register;

The user who left ` /product/product_a_id ` should not receive those event sent to product_a, but he should receive event sent to product_b for he navigated there.

For its in the same liveview, I have to add logics in handle_params to detect url changed then unsub, sub product_id related things.

are there some tools do this more elegantly ?

Thanks !

Most Liked

krasenyp

krasenyp

You basically need a piece of code which filters the pubsub events based on the currently viewed product. I don’t think theres a much better solution to what you have - using handle_params. You can subscribe to receive all the pubsub messages of the background jobs and filter in handle_info based on the identifier of the currently viewed product. This avoids the unsubscribe/subscribe dance but introduces more messages in the mailbox.

garrison

garrison

Unfortunately LiveView lacks the primitives needed to perform generalized incremental computation. For example React has useEffect() and useMemo(), but Phoenix lacks even a full implementation of the older (inferior) lifecycle paradigm: it has mount() and update(), but no unmount().

This makes interop between declarative and imperative code rather… difficult.

Of course you can abandon the incremental approach entirely. The root of the LiveView can subscribe to everything and then meter updates out to individual components.

def handle_info({:product_update, message}, socket) do
  send_update Components.ProductA, id: "product-a", message: message
  send_update Components.ProductB, id: "product-b", message: message
  send_update Components.ProductSidebar, id: "product-sidebar", message: message
  # ...
end

But now, and this kind-of hints at the problem, the structure of your application has become entirely rigid and static. Yes you can unmount A or B and the messages will be ignored, but you have lost the ability to dynamically subscribe. The ability to dynamically mount/unmount components and incrementalize computation is the fundamental raison d’etre for React-style engines, and LiveView is unfortunately derelict of its duty in this department.

If you’re clever you might think you could transmit subscriptions from dynamically mounted components back up to the root. Believe me, I thought that too. But putting aside for the moment that component ids in Phoenix don’t compose (an unrelated issue), this is still insufficient. You cannot tell if a component has been unmounted, so there is no way for a component to clean up after itself.

Right about now some of you may be getting some ideas about how you might hook into the code that leads to an unmount, upstream, and unsubscribe there. Like at the router level, or in response to an event. Let me stop you right there: you are giving up not only incrementalization, but declarative programming as a whole. You are writing imperative code and will be cursed by the gods. Many stronger than you have ventured down this path, and all have fallen. Abandon hope, all ye who enter here.

To be clear, there is no fundamental or technical reason why LiveView cannot provide this functionality. Instead I think it’s mostly a cultural difference; that is to say, most of the devs using LiveView do not understand or need any of this, and would probably get by just fine with something like HTMX if they didn’t happen to be writing Elixir. I used to think that it would be a good idea to extend LiveView with more incremental functionality, but in reality the depth of the changes needed would likely serve to annoy those who don’t want, need, or understand them in the first place. Plus it’s not like I’m volunteering to do the work.

It will likely be easier to write a new framework from scratch.

(And in general I do think it would be nice to have more app frameworks in Elixir, which is why I’m rooting for Hologram!)

TLDR: No, not really.

rhcarvalho

rhcarvalho

As far as I know, your intuition is right, implement conditional deregistration and registration as part of handle_params/3 (possibly extracted into a defp helper.)

If you don’t already, store the current product ID in an assign. You can assign it to nil on mount/3, so that in handle_params/3 you can easily distinguish if you just started and there’s no state to clean up, or if you navigated between products. Assign the current product ID in the handle_params/3 callback.

Don’t forget to check the current product ID in your handle_info/2 callback, and discard messages unrelated to the current product.

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
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
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36352 110
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31265 143
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43757 214
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement