How to use Presence to track users

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:

But you can pass it the topic directly from anywhere. :slight_smile:

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

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. :wink:

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. :slight_smile: