我正在构建一个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
添加到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
当用户离开聊天时,我想删除元信息但保持在线状态。我怎么能这样做?
由于
答案 0 :(得分: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}")