elixirphoenix-frameworkendpointphoenix-channels

Elixir/Phoenix Endpoint broadcast from another module


I have a channel, which does some things in back-end when you connect to it. I need to send response back, once the back-end job is completed. Here is my channel:

  def join("boot", _, socket) do
    Launcher.start()
    {:ok, socket}
  end

  def handle_in("boot:fetch", params, socket) do
    payload = %{total_reports: 5}
    {:reply, {:ok, payload}, socket}
  end

And Launcher module is:

defmodule App.Launcher do
  alias App.Endpoint

  def start() do
    Endpoint.broadcast! "boot", "test:my", %{total_reports: 541}
  end
end

I expected to first receive %{total_reports: 541} on test:my and then %{total_reports: 5} on boot:fetch in the front-end. But I only receive data from boot:fetch and not test:my.

Endpoint.broadcast from Launcher module is not broadcasting anything. Is it expected behaviour? Why can't I broadcast from the modules aliased by channel?

Additionally, I have tested putting the exact same line in channel, and it works. For some reason I cannot do it only with others modules. This example works:

def handle_in("boot:fetch", params, socket) do
    payload = %{total_reports: 5}
    Endpoint.broadcast! "boot", "test:my", %{total_reports: 541}
    {:reply, {:ok, payload}, socket}
end

Solution

  • My mistake was calling Endpoint.broadcast when joining the channel, but as the connection has not yet been established it couldn't broadcast. Moved in into handle in and everything works.

    def join("boot", _, socket) do
      {:ok, socket}
    end
    
    def handle_in("boot:fetch", params, socket) do
      Launcher.start()
      payload = %{total_reports: 5}
      {:reply, {:ok, payload}, socket}
    end