Run code after user joins Channel

I’m using Phoenix Channels in my app.

Say, I want to send user “Hello” message after he joins the channel.
Consider this pseudocode:

  def join("user:" <> user_id, params, socket) do
    UserContext.send_hello(user_id) # broadcasts to "user:<user_id>" topic
    {:ok, socket}
  end

It doesn’t work. The problem, I think, is this broadcasts “hello” message to the topic before user “finished” joining the channel. I can see in server logs that first “hello” function runs, and only then I get [info] JOINED user:a7cf7525-68a6-4b51-bc64-19fdef7f58b7 in 12ms

What’s the best way to run code after user is “joined”?

1 Like
  def join("user:" <> user_id, params, socket) do
    send(self(), {:after_join, user_id})
    {:ok, socket}
  end

  def handle_info({:after_join, user_id}, socket) do
    UserContext.send_hello(user_id) # broadcasts to "user:<user_id>" topic
    {:noreply, socket}
  end
6 Likes