Quick Reference for AI Agents & Developers
- Kotlin
- Java
Real-time Presence
As a logged-in user, how do I know if a user is online or offline? Based on the settings provided in theAppSettings class while initializing CometChat using the init() method, the logged-in user will receive the presence for other users in the app.
In the AppSettings class, you can set the type of presence you wish to receive.
For presence subscription, the AppSettingsBuilder provides 3 methods:
subscribePresenceForAllUsers()- Informs the logged-in user when any user in the app comes online or goes offline.subscribePresenceForRoles(List<String> roles)- Informs the logged-in user only when users with the specified roles come online or go offline.subscribePresenceForFriends()- Informs the logged-in user when any of their friends come online or go offline.
UserListener using the addUserListener() method.
We suggest adding the listener in the onResume() method of the activity or fragment where you wish to receive these events.
- Java
- Kotlin
| Parameter | Description |
|---|---|
listenerID | An ID that uniquely identifies that listener. We recommend using the activity or fragment name. |
User class in the listener methods.
We recommend removing the listener once the activity or fragment is not in use. We suggest adding this method in the onPause() method of the activity or fragment where you wish to receive these events.
- Java
- Kotlin
User List Presence
As a logged-in user, when I retrieve the user list, how do I know if a user is online/offline? When you retrieve the list of users, in the User object, you will receive 2 keys:status- This holds either of the two values:
online- Indicates that the user is currently online and available to chat.offline- Indicates that the user is currently offline and not available to chat.
lastActiveAt- If the user is offline, this field holds the timestamp of when the user was last online. This can be used to display a Last seen indicator for that user.
Best Practices
Choose Appropriate Subscription Type
Choose Appropriate Subscription Type
Use
subscribePresenceForAllUsers() for small communities (under 1000 users), subscribePresenceForFriends() for social apps where users have friend lists, or subscribePresenceForRoles() for role-based presence to optimize performance and reduce unnecessary presence updates.Handle Presence Updates Efficiently
Handle Presence Updates Efficiently
Batch presence updates in your UI to avoid excessive re-renders when multiple users change status simultaneously. Consider debouncing presence updates if you’re displaying a large user list.
Use lastActiveAt for Offline Users
Use lastActiveAt for Offline Users
Display a “Last seen” indicator using the
lastActiveAt timestamp for offline users to provide better context about user availability.