fetch active users on mount

This commit is contained in:
Berenice Medel 2022-01-27 14:14:01 -06:00
parent d93bb8e810
commit b8608bc77d
2 changed files with 33 additions and 19 deletions

View file

@ -1,7 +1,7 @@
defmodule LiveBeats.UserTracker do defmodule LiveBeats.UserTracker do
use GenServer use GenServer
@pubsub LiveBeats.PubSub @pubsub LiveBeats.PubSub
@poll_interval :timer.seconds(5) @poll_interval :timer.seconds(30)
@doc """ @doc """
TODO TODO
@ -15,6 +15,10 @@ defmodule LiveBeats.UserTracker do
GenServer.start_link(__MODULE__, opts, name: __MODULE__) GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end end
def list_active_users() do
GenServer.call(__MODULE__, :list_users)
end
def presence_joined(presence) do def presence_joined(presence) do
GenServer.call(__MODULE__, {:presence_joined, presence}) GenServer.call(__MODULE__, {:presence_joined, presence})
end end
@ -28,6 +32,11 @@ defmodule LiveBeats.UserTracker do
{:ok, schedule_updates(%{})} {:ok, schedule_updates(%{})}
end end
@impl true
def handle_call(:list_users, _from, state) do
{:reply, list_users(state), state}
end
@impl true @impl true
def handle_call({:presence_joined, presence}, _from, state) do def handle_call({:presence_joined, presence}, _from, state) do
{:reply, :ok, handle_join(state, presence)} {:reply, :ok, handle_join(state, presence)}
@ -70,11 +79,14 @@ defmodule LiveBeats.UserTracker do
end end
defp broadcast_updates(state) do defp broadcast_updates(state) do
active_users = Phoenix.PubSub.local_broadcast(
state @pubsub,
|> Enum.map(fn {_key, value} -> value end) topic(),
{LiveBeats.UserTracker, %{active_users: list_users(state)}}
Phoenix.PubSub.local_broadcast(@pubsub, topic(), {LiveBeats.UserTracker, %{active_users: active_users}}) )
end end
defp list_users(state) do
Enum.map(state, fn {_key, value} -> value end)
end
end end

View file

@ -1,14 +1,15 @@
defmodule LiveBeatsWeb.Nav do defmodule LiveBeatsWeb.Nav do
import Phoenix.LiveView import Phoenix.LiveView
alias LiveBeats.UserTracker
alias LiveBeatsWeb.{ProfileLive, SettingsLive} alias LiveBeatsWeb.{ProfileLive, SettingsLive}
def on_mount(:default, _params, _session, socket) do def on_mount(:default, _params, _session, socket) do
if connected?(socket) do if connected?(socket) do
LiveBeats.UserTracker.subscribe() UserTracker.subscribe()
end end
socket socket
|> assign(:active_users, []) |> assign(:active_users, UserTracker.list_active_users())
|> assign(:region, System.get_env("FLY_REGION")) |> assign(:region, System.get_env("FLY_REGION"))
|> attach_hook(:active_tab, :handle_params, &handle_active_tab_params/3) |> attach_hook(:active_tab, :handle_params, &handle_active_tab_params/3)
|> attach_hook(:ping, :handle_event, &handle_event/3) |> attach_hook(:ping, :handle_event, &handle_event/3)
@ -20,6 +21,7 @@ defmodule LiveBeatsWeb.Nav do
{:cont, socket} {:cont, socket}
end) end)
{:cont, socket} {:cont, socket}
end end