Broadcast from iex not working

Hi Folks,

I am working on small phoenix live view application. I have created method which will broadcast after inserting/updating and there is a live view which subscribed to that event and re-renders. If i update via postman everything works as expected. But it is not working from iex shell.

Methods in context

 def update_hit_count(%ApiHit{} = api_hit, attrs) do
    api_hit
    |> change_api_hit(attrs)
    |> Repo.update()
    |> broadcast(:api_hit_updated)
  end

def subscribe do
    Phoenix.PubSub.subscribe(Bramble.PubSub, "users")
  end

  defp broadcast({:error, _reason} = error, _event), do: error

  defp broadcast({:ok, user}, event) do
    Phoenix.PubSub.broadcast(Bramble.PubSub, "users", {event, user})
    {:ok, user}
  end

Live view methods

def mount(_params, _session, socket) do
    if connected?(socket), do: Accounts.subscribe()

    {:ok,
     socket
     |> assign(:user_list, Accounts.api_hits_list()), temporary_assigns: [user_list: []]}
  end

 @impl true
  def handle_info({:api_hit_updated, _api_hit}, socket) do
    {:noreply, update(socket, :user_list, fn _user_list -> Accounts.api_hits_list() end)}
  end

I am doing this in my shell, But it is not refreshing my page. But if update via postman it works.

iex(33)> api_hit = Accounts.get_api_hit(%{id: 45})
iex(34)> Accounts.update_hit_count(api_hit, %{hits: 998})

What if you comment out def handle_info({:api_hit_updated, _api_hit}, socket) do, do you get a crash? Are iex and the node where liveview is running connected?

1 Like

Nothing happened when i commented out the handle_info. I think my server and iex shell are not connected.
When I tried to do the same in iex -S phx.server It worked. How to connect mix phx.server and iex -S mix ?

1 Like

You are correct that if you are running two separate beam processes they don’t talk to each other by default. You can run iex with the --remsh argument to connect to another node, such as your server process and then broadcasts you send will be sent to subscribers connected to the websocket served by that process.

As an example of how to make this work you need to supply node names to both processes, so you’d run your web server process with a command like this:

MIX_ENV=prod elixir --name phoenix@127.0.0.1 -S mix phx.server

And then you can run a console on the same machine with a command like this:

iex --name "console@127.0.0.1" --remsh "phoenix@127.0.0.1"
6 Likes

Awesome it worked :slight_smile:

this should be on the phoenix pubsub documentation for saving time :joy:

1 Like