gpt4 book ai didi

elixir - Phoenix Presence 通过交替元数据跨多个 channel 跟踪用户

转载 作者:行者123 更新时间:2023-12-02 05:15:22 30 4
gpt4 key购买 nike

我正在构建一个 Whatsapp 克隆,但无法通过 Presence 找出一些内容。

我有两个 channel :

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

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

  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

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

谢谢

最佳答案

实际上它是开箱即用的,以下测试表明了这一点:

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

关于elixir - Phoenix Presence 通过交替元数据跨多个 channel 跟踪用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37730922/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com