0

I probably have a wrong mental model of how sockets and channels work in Phoenix. This is the scenario that confuses me:

I declare two channels under the same socket:

defmodule MyAppWeb.TestSocket do
  channel("a:*", MyAppWeb.AChannel)
  channel("b:*", MyAppWeb.BChannel)
end

I perform socket assignment in the connect function of the socket module:

  def connect(payload, socket) do
       {:ok, assign(socket, :foo, 1)}
  end

Then in the handle_in function of channel A, I perform some further assignments:

defmodule MyAppWeb.AChannel do
  def handle_in("example_msg", payload, socket) do
      {:reply, :ok, assign(socket, :new_key, "aaa")}
  end
end

However, when the client then tries to join channel B, channel B doesn't seem to pick up this :new_key.

defmodule MyAppWeb.BChannel do
  def join("b:" <> room_identifier, _payload, socket) do
    # Only contains :foo
    IO.inspect(socket)
    # ...
  end
end

The socket only contains :foo, but not the :new_key assigned in channel A.

Am I doing the wrong thing by trying to let channel B access a socket modified by channel A? I thought that since the client is only connected to the server via one single socket, any modifications to its assigns should also be shared across the channels, just like how all channels see the :foo key assigned during the initial socket connection. However, this doesn't seem to be the case.

xji
  • 7,341
  • 4
  • 40
  • 61
  • 2
    It is by design as "a.*" and "b.*" are different topics. It is explained in detail in the [official doc](https://hexdocs.pm/phoenix/channels.html). Basically when you establish a connection with one channel you subscribe to a specific topic. So you will get updates only to this specific topic. I don't think it's intended to get updates from topic B in topic A. – Denis Tataurov Dec 23 '22 at 07:14

0 Answers0