almeynman
almeynman

Reputation: 7398

Phoenix Presence track user across multiple channels with alternating meta

I am building a whatsapp clone and having trouble figuring out some stuff with Presence.

I have two channel:

  channel "chats:*", Typi.ChatChannel
  channel "users:*", Typi.UserChannel

The user is always connected to users:... channel, if he is in the app, and on join I start tracking his presence:

  def join("users:" <> user_id, _payload, socket) do
    send self(), :after_join
    {:ok, socket}
  end

  def handle_info(:after_join, socket) do
    Presence.track(socket, socket.assigns.current_user.id, %{})
    {:noreply, socket}
  end

When user joins some chat I add chat_id to meta:

  def join("chats:" <> chat_id, _payload, socket) do
    send self(), :after_join
    {:ok, assign(socket, :current_chat, chat)}
  end

  def handle_info(:after_join, socket) do
    Presence.track(socket, socket.assigns.current_user.id, %{
      chat_id: socket.assigns.current_chat.id
    })
    {:noreply, socket}
  end

When the user leaves the chat I want to delete meta information but keep the presence. How can I do that?

Thanks

Upvotes: 4

Views: 1153

Answers (1)

almeynman
almeynman

Reputation: 7398

Actually it works out of the box, the following test shows it:

  test "presence test", %{socket: socket, users: [john], chat: chat} do
    {:ok, _, user_socket} = subscribe_and_join(socket, "users:#{john.id}", %{})
    IO.inspect Presence.list(user_socket)
    {:ok, _, chat_socket} = subscribe_and_join(socket, "chats:#{chat.id}", %{})
    IO.inspect Presence.list(chat_socket)
    IO.inspect Presence.list(user_socket)
  end

The output of the test is:

%{"7939" => %{metas: [%{phx_ref: "UZDsMseg3as="}]}}
%{"7939" => %{metas: [%{chat_id: 1392, phx_ref: "sRhw30CJY1U="}]}}
%{"7939" => %{metas: [%{phx_ref: "UZDsMseg3as="}]}}

Also Presence.list(chat_socket) == Presence.list("chats:#{chat.id}")

Upvotes: 2

Related Questions