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

View file

@ -1,26 +1,28 @@
defmodule LiveBeatsWeb.Nav do
import Phoenix.LiveView
alias LiveBeats.UserTracker
alias LiveBeatsWeb.{ProfileLive, SettingsLive}
def on_mount(:default, _params, _session, socket) do
if connected?(socket) do
LiveBeats.UserTracker.subscribe()
UserTracker.subscribe()
end
socket
|> assign(:active_users, [])
|> assign(:region, System.get_env("FLY_REGION"))
|> attach_hook(:active_tab, :handle_params, &handle_active_tab_params/3)
|> attach_hook(:ping, :handle_event, &handle_event/3)
|> attach_hook(:actie_users, :handle_info, fn
{LiveBeats.UserTracker, %{active_users: users}}, socket ->
{:halt, assign(socket, :active_users, users)}
socket
|> assign(:active_users, UserTracker.list_active_users())
|> assign(:region, System.get_env("FLY_REGION"))
|> attach_hook(:active_tab, :handle_params, &handle_active_tab_params/3)
|> attach_hook(:ping, :handle_event, &handle_event/3)
|> attach_hook(:actie_users, :handle_info, fn
{LiveBeats.UserTracker, %{active_users: users}}, socket ->
{:halt, assign(socket, :active_users, users)}
_params, socket ->
{:cont, socket}
_params, socket ->
{:cont, socket}
end)
{:cont, socket}
end)
{:cont, socket}
end
defp handle_active_tab_params(params, _url, socket) do