#Convert PubSub into Endpoint

8 messages · Page 1 of 1 (latest)

sterile anchor
#

I have two (modules) pages of code below. One named send.ex, and the other named receive.ex . I use PubSub.broadcast and PubSub.subscribe to send a message from send.ex to receive.ex . It works and does what I expect. I want to know how to rewrite it using Endpoint.subscribe and Endpoint.broadcast.

send.ex

defmodule AppWeb.SendLive do
  use AppWeb, :live_view

  def mount(_params, _session, socket) do
    {:ok, socket}
  end

  def handle_event("send", %{"text" => text}, socket) do
    Phoenix.PubSub.broadcast(App.PubSub, "message", {:pubsub_transmission, text})
    {:noreply, socket}
  end


  def render(assigns) do
    ~H"""
    <div>
      <h1>Send Message</h1>
      <form phx-submit="send">
        <input type="text" name="text" />
        <button type="submit">Send</button>
      </form>
    </div>
    """
  end
end

received.ex

defmodule AppWeb.ReceiveLive do
  use AppWeb, :live_view

  def mount(_params, _session, socket) do
    if connected?(socket) do
      Phoenix.PubSub.subscribe(App.PubSub, "message")
    end

    {:ok, assign(socket, message_item: "")}
  end

  def handle_info({:pubsub_transmission, text}, socket) do
    {:noreply, assign(socket, message_item: text)}
  end

  def render(assigns) do
    ~H"""
    <div>
      <h1>ChatLive</h1>
      <%= @message_item %>
    </div>
    """
  end
end


jaunty kiln
#

Why do you want to do that? This works and is the intended way to use Phoenix PubSub with LiveView.

#

The endpoint functions end up just calling these functions in the end anyway, so to me it seems like just adding extra steps for no real gain.

sterile anchor
#

I see it done both ways and I figure I should know how to do it the other way if I "really" want to understand it. I'm not sweating it and it's ressuring to know it doesn't much matter

jaunty kiln
#

If you really want to understand it, I would go read the source code of the endpoint functions, that's what I just did before responding here

#

gimme a sec and I'll post some links

#

broadcast is slightly more complicated, you can see here that it calls into a different function from phoenix channels: https://github.com/phoenixframework/phoenix/blob/v1.7.10/lib/phoenix/endpoint.ex#L453
which is right here: https://github.com/phoenixframework/phoenix/blob/main/lib/phoenix/channel/server.ex#L141
which just wraps the message into a struct and just calls Phoenix.PubSub.broadcast.
So my initial assesment is correct: it's essentially the same thing as what you're already doing but with more steps. I prefer to define my own PubSub structs so, losing the built-in Phoenix.Socket.Broadcast struct isn't a big loss imo