Reputation: 1177
If a user has joined a topic, say "rooms:lobby"
and then the user joins another sub topic on the same channel, like "rooms:party"
. How can I force the user to be leave "rooms:lobby" from the backend. I have tried filtering the broadcast, but haven't had any luck. I would prefer to just terminate connection to old sub topics over filtering broadcasts.
defmodule MyApp.RoomsChannel do
use Phoenix.Channel
intercept ["new_msg"]
def join("rooms:" <> room_id, _params, socket) do
{:ok, assign(socket, :room_id, room_id)
end
def handle_out("new_msg", payload, socket) do
if current_room?(socket.assigns[:room_id], socket.topic) do
push socket, "new_msg", payload
{:noreply,socket}
else
{:noreply, socket}
end
end
defp current_room?(room_id, "rooms:" <> sub_topic) do
room_id == sub_topic
end
end
I know it's possible to leave a topic from the front-end, but I need to ensure that only they current topic they are viewing gets the payload and not any of the previous topics that where subscribed to on a particular channel.
Upvotes: 3
Views: 1270
Reputation: 26
From your comments it sounds like you are trying to join 1 channel per route, and you want to switch channels when the route changes instead of accumulating multiple channels. My guess is you are joining the channel inside of a lifecycle method (e.g. ComponentWillMount) from a high level React component.
If so, why not terminate the channel from the client in ComponentWillUnmount? This should fire just before your route changes on the client.
Upvotes: 1