Accessing gen_server linked to the socket

Hello, I created my first live route:

live "/living", LivingController

and then added some event handling code:

def handle_event("off", _, socket) do
  socket = assign(socket, :knob, 0)
  IO.inspect(socket, structs: false)
  {:noreply, socket}
end

I can now see the socket printed to the terminal with IO.inspect.

How could I find out which is the pid of the process running the gen_server, which stores the assigns? Can I change the value for assigns.knob in the terminal? (and see if the new value shows up in the browser).
Those are not practical questions - I am just tinkering with stuff.

The code in handle_event runs in the process that’s holding assigns - you can get its PID with self()

1 Like

Ah - that easy.

OK - so now I have the PID, and after :sys.trace(pid(0,5120,5), true) I am able to see the process data with :sys.get_state(pid(0,5120,5)). Are there any generic messages I could send to this process? For example, can I create a new key inside socket.assigns by just sending a message?

%{
  components: {%{}, %{}, 1},
  join_ref: "77",
  serializer: Phoenix.Socket.V2.JSONSerializer,
  socket: #Phoenix.LiveView.Socket<
     ...
     assigns: %{__changed__: %{}, flash: %{}, knob: 0, live_action: nil},

There’s no built-in way to do this, but your LiveView can define handle_info/2 callbacks that handle arbitrary messages.

This is usually used for communicating between parts of the LiveView (for instance, sending data from a child LiveComponent back to the parent) but anything that has the LiveView’s PID can send messages.

1 Like