dwyl / phoenix-liveview-chat-example

💬 Step-by-step tutorial creates a Chat App using Phoenix LiveView including Presence, Authentication and Style with Tailwind CSS

Home Page:https://liveview-chat-example.fly.dev/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add Presence

SimonLab opened this issue · comments

commented

Use Presence to display of loggedin people.

commented

Add Presence

We first need to add the presence features to the application. The first part of the documentation explains how to do this https://hexdocs.pm/phoenix/Phoenix.Presence.html#module-example-usage

  • Create a new presence.ex file in lib/liveview_chat/ folder with the following content:
defmodule LiveviewChat.Presence do
  use Phoenix.Presence,
    otp_app: :liveview_chat,
    pubsub_server: LiveviewChat.PubSub
end

Then in lib/liveview_chat/application.ex we start Presence by adding it to the list of children in the start function:

    children = [
      # Start the Ecto repository
      LiveviewChat.Repo,
      # Start the Telemetry supervisor
      LiveviewChatWeb.Telemetry,
      # Start the PubSub system
      {Phoenix.PubSub, name: LiveviewChat.PubSub},
      # Presence
      LiveviewChat.Presence,
      # Start the Endpoint (http/https)
      LiveviewChatWeb.Endpoint
      # Start a worker by calling: LiveviewChat.Worker.start_link(arg)
      # {LiveviewChat.Worker, arg}
    ]

Now we can use the Presence features to listen to people using the app.

Track new user on mount

We know that a new user is using the chat message when the mount liveview function is called.
We use the track/3 function to know the status of a user.

     if socket.assigns.loggedin do
        person_id = socket.assigns.person["id"]
        person_name = socket.assigns.person["givenName"]

        {:ok, _} =
          Presence.track(self(), "liveview_chat_presence", person_id, %{name: person_name})
      end

At the moment we only track loggedin people, so we use

Listen for join/leave event

We use PubSub to listen for the presence_diff event which is sent each time a person join or leave the message page.
see https://github.com/dwyl/phoenix-liveview-chat-example/pull/19/files#diff-134a4301c7f509ba9b9db8e47063430f9d4a0b48e6ae7c6dbe7f58540a93093cR24

commented

PR ready for review at #19

Superb addition. Thanks @SimonLab 👍