Phoenix Presence track users across multiple channels

363 Views Asked by At

So I want to keep track of the current room of each user using the presence behavior. The problem is that I can't/don't know how to update the room_id if a user changes its current room.

def join("room:" <> room_id, auth_message, socket) do IO.puts "joining room:" <> room_id if authorized?(room_id, socket) do {:ok, assign(socket, :room_id, room_id)} else {:error, %{reason: "unauthorized"}} end end

I pass the room_id when a user joins a room and then i made this handler for when he changes between rooms:

 def handle_in("room:changed", %{"room_id" => room_id, "user_id" => user_id}, socket) do
    IO.puts "user moved to room #{inspect room_id} "
    Presence.track(socket, socket.assigns.user_id, %{room_id: socket.assigns.room_id})
    IO.inspect(Presence.list(socket))
    push socket, "presence_state", Presence.list(socket)
    {:noreply, socket}
  end

The thing is that for every room he clicks on there is a new entry in the list, so basically he is in all those rooms at the same time. What I want is to only update the room_id when he moves away.

1

There are 1 best solutions below

0
On

A Channel has a terminate/2 callback which you could use to update presence.

def terminate(reason, _socket) do
  Logger.debug"> leave #{inspect reason}"
  :ok
end