积极从Elixir的聊天频道中删除用户

时间:2018-04-11 10:34:34

标签: elixir chat otp

我是Elixir的初学者,我正在开发一个有多个频道的简单聊天服务器。

我的频道是GenServer,它存储了一个用户列表(pids),还有一个地图(用户参考 - > pid)来处理用户进程崩溃(来自Elixir Guides) 。但是因为它是一个以refs为键的地图,当我实现remove_member_from_channel函数时,我想删除pid(地图的值),我该怎么办呢?或者我选择了错误的方法来实现它?

defmodule Chat.Channel do
  use GenServer

  # ......

  def add_member(channel, user) do
    GenServer.call(channel, {:add_member, user})
  end

  def remove_member(channel, user) do
    GenServer.call(channel, {:remove_member, user})
  end

  # ......

  def handle_call({:add_member, user}, _from, {members, refs}) do
    if Enum.member?(members, user) do
      {:reply, :already_added, {members, refs}}
    else
      new_members = [user | members]
      ref = Process.monitor(user)
      new_refs = Map.put(refs, ref, user)
      {:reply, :ok, {new_members, new_refs}}
    end
  end

  def handle_call({:remove_member, member}, _from, {members, refs}) do
    if Enum.member?(members, member) do
      new_members = List.delete(members, member)

      # What to do with refs??

      {:reply, :ok, {new_members, refs}}
    else
      {:reply, :member_not_added, {members, refs}}
    end
  end

  def handle_info({:DOWN, ref, :process, _pid, _reason}, {members, refs}) do
    {member, new_refs} = Map.pop(refs, ref)
    new_members = List.delete(members, member)
    {:noreply, {new_members, new_refs}}
  end
end

1 个答案:

答案 0 :(得分:0)

使用Enum.filter/2(或Enum.reject/2

def handle_call({:remove_member, member}, _from, {members, refs}) do
  if Enum.member?(members, member) do
    new_members = List.delete(members, member)
    new_refs =
      Enum.filter(refs, fn
        {_ref, ^member} -> false
        _ -> true
      end)
    {:reply, :ok, {new_members, refs}}
  else
    {:reply, :member_not_added, {members, refs}}
  end
end

一般情况下,我最好存储used_id ⇒ reference地图,例如:

new_refs = Map.put(refs, user, ref) # or even better used.id

这样可以稍后使用Map.delete/2

...
  new_members = List.delete(members, member)
  new_refs = Map.delete(refs, member) # or member.id