4

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

我有两个频道:

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

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

  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到元:

  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

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

谢谢

4

1 回答 1

2

实际上它是开箱即用的,下面的测试显示了它:

  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("chats:#{chat.id}")

于 2016-06-10T09:04:12.577 回答