Sending messages between clients NOT subscribed to channel:topic?

User A makes a socket connection and “user:A” channel/topic is created. This channel will be used for all application specific data (will mimic classic HTTP req/res pattern) for this user. The same thing will happen when user B connects.

User A views user’s B profile, perhaps sends this user an email basically does something that user B might be interested in knowing.

These users are not subscribed to the same channel:topic. Therefore how can I propagate this specific event (for example “user A viewed your profile”) from user’s A socket over to user’s B socket?

One possible solution would be to have two channels (one public to which all users subscribe and one private) for all users but I don’t want to notify user C that user A visited user’s B profile. This event would have been propagated to all connected clients over the public channel, which is not really what I’d want (seems like a waste of resources to send a message to N users when only one is interested).

Is there a way to filter this somehow? Would I have to filter/ignore on the client side?

I’m on mobile so I’ll keep it short. But as I understand you, you can do a global channel that everyone joins and use handle_out to do the filtering before actually sending the message over the network.

Just send an Endpoint.broadcast call to whatever topic you want to receive the message.

You broadcast directly to their topic.

From User A’s channel:

MyApp.Endpoint.broadcast!("user:#{user_b_id}", "profile_view", %{
  by_user_id: socket.assings.user_id
})

And that’s all there is to it. The same rules apply as broadcasting to external topics from anywhere in the cluster. See this section in the docs for more details:
https://github.com/phoenixframework/phoenix/blob/f2e02d97ef79f825f6bbbdc2d7b69a1d005bff90/lib/phoenix/channel.ex#L130

3 Likes

Thanks guys, I appreciate your help!

just a questions: if I have hundred of thousands of users, Is creating a topic for every connected user a good solution ?

I certainly hope so because each of my sockets have about 10 topics each for various purposes… >.>

Yes :rocket:

3 Likes

Glad to be vindicated! Always worried I’d eventually hit some unknown limit. :slight_smile:

I use topics excessively for connecting to various services and for each of broadcasting. :slight_smile: