Imagine this familiar situation. We have a LiveView that renders a list of posts. Each post has an author (user) and multiple comments. Each comment also has an author (user). The LiveView process subscribes to some “new comment” topic. When a new comment is created on a post, this information is broadcast.
In this situation, it is clear that the PubSub payload should include the comment’s author preloaded. This could be a new user, who registered after the LiveView mounted. All is good.
Now imagine a different situation. We have a LiveView that renders a restaurant menu. A user can add items to their basket. A basket can be shared, so multiple users are using the same basket. The LiveView process subscribes to some “new basket item” topic. When an item is added to the basket, this information is broadcast. The LiveView is also subscribed to menu changes, e.g. menu item price changes. This means the LiveView process “knows” all the menu details.
In this situation, the basket item is associated to a menu item. My scruple is this: should the PubSub payload include the menu item preloaded on the created basket item struct? It seems wasteful, since, assuming our LiveView also subscribes to menu updates, the LiveView already “knows” the menu item details (not using streams here). Moreover, if, say, a menu item price changes, we will need update all assigned basket items that have this menu item preloaded.
With this in mind, it seems silly to trust/use a basket item’s preloaded menu item association. So I naturally think “OK, I will just find the menu item in the menu assign and infer details from that for rendering the basket item”. However, my menu items are a list, and iterating over a list for every basket item render is obviously very bad. OK, so maybe I should instead have a map of menu item IDs to menu items? Now the code feels very unwieldy, since I am perpetually transforming lists into maps, just for easy access of assoc details.
This entire train of thought has been a thorn in my side while doing LiveView development. I feel like no matter which approach I take, I am begetting obvious inefficiency.
Does anyone else feel this way? Does anyone have ancient secrets of efficient nested association assigns they want to share?
P.S. I love LiveView. It is awesome. I use it every day.