Access LiveView assigns from another process

When mounting my live view, I register it as a participant in a running GenServer.

def mount(_params, _session, socket) do
  MyGenServer.add_participant(self())
  {:ok, socket}
end

This allows me to easily work with a list of participants very easily. I now introduced some JS dependency which creates a unique ID for each participant/rendered live view and pushes it back to the server, which stores it in its assigns. However for my app to properly work, I would need a list of these unique IDs across all my participants. This can be done via :sys.gen_state, but feels very wrong.

MyGenServer.participants() 
|> Enum.map(fn participant → 
  :sys.gen_state(participant)
  |> Map.get(:socket)
  |> Map.get(:assigns)
end)

Is there an official way to get assigns from a live-view process from outside of the process?

I wouldn’t really recommend thinking this way. Assigns belong to the socket. What do you need them for in the genserver?

I need a way to share the assigns across all my live views. Each live view gets a unique ID, and the other live views connected to the server should see this unique ID. (I need this ID to connect all users to a video channel.)

I would consider using something like Registry so that each live view could register its unique ID.

This sounds like an XY problem. Each live view is a different process, process state isn’t really shareable. You can message it around, but it’s gonna get copied each time and isn’t going to stay up to date as the process state changes. It’s fine to message around the ID, but I wouldn’t do so for the full assigns. Can you elaborate on what you’re trying to do more?

3 Likes