elie
May 8, 2017, 9:54pm
1
I have code like this in my app:
{:ok, _} = Presence.track(socket, socket.assigns.user_id, %{
online_at: inspect(System.system_time(:milli_seconds))
})
Presence.list(socket) |> IO.inspect
I’d like yo use the info from Presence.list in another module in the app. How do I go about doing this?
And will online_at be the time the user was last online?
Thanks
You can use it from anywhere else just fine. Presence.list/1
accepts a topic. It also has an override that grabs a topic out of a socket then just calls itself again as seen at:
# event to all subscribers
for {user_id, presence} <- leaves do
metas =
case Map.fetch(presences, user_id) do
{:ok, presence_metas} -> presence_metas
:error -> []
end
user_data = %{user: presence.user, metas: metas}
msg = {MyApp.PresenceClient, {:leave, user_data}}
Phoenix.PubSub.local_broadcast(MyApp.PubSub, topic, msg)
end
{:ok, state}
end
end
The `handle_metas/4` callback receives the topic, presence diff, current presences
for the topic with their metadata, and any user-land state accumulated from init and
subsequent `handle_metas/4` calls. In our example implementation, we walk the `:joins` and
`:leaves` in the diff, and populate a complete presence from our known presence information.
But you can pass it the topic directly from anywhere.
You’ll have a set of those online_at’s for each one being tracked and they will each have a time based on when that code was executed (I.E. the tracking started).
2 Likes
elie
May 9, 2017, 3:43pm
3
So to get the latest time a user was online I’d have to do track on every action the user makes?
But if I just want to know if the user was online I can just if the user is in the list?
Well if they are still in the list at all then they ‘are’ still active.
If they are not in the presence list then they are gone
If you want to store when they were ‘last’ active instead of when they became active then store that on disconnect, like in a database.