我的 Phoenix 1.5.8 LiveView 应用程序使用phx_gen_auth进行用户身份验证。
- 我将当前登录的用户分配给
@current_user
. - 我将当前访问者的数量(无论是否登录)分配给
@current_visitors_count
.
现在我想用来@current_users_count
显示以用户身份登录的访问者数量。但我不知道如何在handle_info
. 计算两个数字的最佳方法是什么?
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