Phoenix Presence tracks user through multiple channels with alternating meta

I am creating a whatsapp clone and have difficulty figuring out some things with the Presence.

I have two channels:

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

The user always connects to the channel users:...if it is in the application, and when I connect, I begin to track its 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 the user joins the chat, I add chat_idto the 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 the meta-information, but I keep it. How can i do this?

thank

+4
source share
1 answer

This actually works out of the box, the following test shows this:

  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

Test output:

%{"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}")

+1

All Articles