View Models/Data Helpers/State Management

In the 15 minute twitter video, Chris broadcasts the updated Post event with the entity attached which is then simply appended to the list of Posts. This is a simple operation but it does create a little bit of duplication with the domain code—a Post is added to the conceptual list of Posts in the db, then to the literal list of Posts in the LiveView state. This duplication can get a lot hairier in more complicated scenarios, though. For example, when moving an item from list to another, there are three entities involved: the item along with the source list and destination list. This would result in having to the write that logic in both the view and the domain layers.

Is this generally the route people take? Is it viable to have a view model (or data helper) pre-emptively update the state then sending the result to the db? Is there any disadvantage to that assuming you could blow up on the db update if it fails which would re-render the LiveView in the previous state?

I would love to get some feedback with different ideas on this!


This is imo a fact inherently coupled to the fact that both your db and the liveview process maintain state of a list of things, which you want both to be updated. The simplest option is letting the liveview be a plain consumer and sending it the whole new list. From there it’s optimizations to improve latency, minimize data moved around and such.

Hi! Thanks for your reply!

This is what I’m currently doing but feel it’s pretty inefficient (and actually noticing a tiny bit of lag even locally when there is enough data).

I have I guess what you would call a trello-style application for posting simple post-it-note notes and it has multiple lanes. I’m currently, on every update, re-fetching every single lane with every single note when the position of a note is moved. Of course I could make it a little smarter and just update the affected lane, but then if it’s moved between lanes it gets more complex as I’d have to update two lanes.

But! As you put it, this is an inherit side-effect of separating persistence and app state and I can accept that—I just needed to hear someone else say it :smiley: I think I’m still getting used to Phoenix not being opinionated in the same way that Rails is opinionated and afraid that I’m missing out on a well-known pattern.

Thanks again!

PS, I really enjoy your blog. Your post about user-sorting opened me up to all sorts of new ideas on how to approach it.

If you need the optimization, then feel free to duplicate the business logic and make pubsub only broadcast information about what things moved. But now you’re aware why it’s there to begin with :smiley:

1 Like

Oops, I replied to myself on my note about your blog… ha!