Implement direct messages (no chat room) using phoenix channels

The best way to accomplish this is to have a “control” channel for each user, such as a UserChannel, a topic like user:[user_id]. When User A wants to start a private conversation with User B, they broadcast to User A’s channel:

socket.endpoint.broadcast!("user:b", "open_convo", %{from: "a", room_topic: "priv_room:a:b"})

Then on the client, User A reacts to the event. This would allow your UI to either decline or accept new convos or always join automatically:


userChannel.on("open_convo", ({from: remoteUserID, room_topic: topic}) => {
  let privRoom = socket.channel(topic)
  privRoom.join()
  ....
})

You want to avoid the handle_out usage where all users join the same topic since filtering any individual convo would be extremely expensive. Hope the helps!

17 Likes