elixir – Phoenix Presence跨多个渠道跟踪用户,交替使用meta

我正在构建一个whatsapp克隆,并且无法通过Presence找出一些东西.

我有两个频道:

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

用户总是连接到用户:…频道,如果他在应用程序中,并且在加入时我开始跟踪他的存在:

  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

当用户加入一些聊天时,我将chat_id添加到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

当用户离开聊天时,我想删除元信息但保持在线状态.我怎样才能做到这一点?

谢谢

最佳答案 实际上它开箱即用,以下测试显示:

  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

测试的输出是:

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

还有Presence.list(chat_socket)== Presence.list(“聊天:#{chat.id}”)

点赞