My Phoenix 1.5.8 LiveView application uses phx_gen_auth for the user authentication.
- I assign to currently logged in user to
@current_user
. - I assign the number of current visitors (no matter if logged in or not) to
@current_visitors_count
.
Now I want to use @current_users_count
to display the number of visitors which are logged in as users. But I have no idea how to handle that in handle_info
. What is the best way do count both numbers?
lib/example_web/live/page_live.ex
defmodule ExampleWeb.PageLive do
use ExampleWeb, :live_view
@impl true
def mount(_params, session, socket) do
socket =
socket
|> assign_current_user(session)
|> assign_current_visitors_count()
{:ok, socket}
end
@impl true
def handle_info(
%{event: "presence_diff", payload: %{joins: joins, leaves: leaves}},
%{assigns: %{current_visitors_count: count}} = socket
) do
current_visitors_count = count + map_size(joins) - map_size(leaves)
{:noreply, assign(socket, :current_visitors_count, current_visitors_count)}
end
end
lib/example_web/live/live_helpers.ex
defmodule ExampleWeb.LiveHelpers do
import Phoenix.LiveView
alias Example.Accounts
alias Example.Presence
def assign_current_user(socket, session) do
assign_new(
socket,
:current_user,
fn ->
case session["user_token"] do
nil -> nil
user_token -> Accounts.get_user_by_session_token(user_token)
end
end
)
end
def assign_current_visitors_count(socket) do
topic = "current_visitors"
initial_count = Presence.list(topic) |> map_size
ExampleWeb.Endpoint.subscribe(topic)
Presence.track(
self(),
topic,
socket.id,
%{}
)
assign(socket, :current_visitors_count, initial_count)
end
end