-
Notifications
You must be signed in to change notification settings - Fork 34
Presence
The Presence object provides features for syncing presence information from the server with the client and handling presences joining and leaving.
To sync presence state from the server, first instantiate an object and pass your channel in to track lifecycle events:
val socket = Socket("https://localhost:4000/socket")
val channel = socket.channel("some:topic")
val presence = Presence(channel)
If you have custom syncing state events, you can configure the Presence object to use those instead. By default, the client listens for presence_state
and presence_diff
events on the channel.
val customOptions = Presence.Options(
mapOf(
Presence.Events.STATE to "custom_state",
Presence.Events.DIFF to "custom_diff"
))
val presence = Presence(channel, customOptions)
Next, use the presence.onSync callback to react to state changes from the server. For example, to render the list of users every time the list changes, you could write:
presence.onSync { renderUsers(presence.list()) }
presence.list
is used to return a list of presence information based on the local state of metadata. By default, all presence metadata is returned, but a listBy function can be supplied to allow the client to select which metadata to use for a given presence. For example, you may have a user online from different devices with a metadata status of online, but they have set themselves to away on another device. In this case, the app may choose to use the away status for what appears on the UI. The example below defines a listBy function which prioritizes the first metadata which was registered for each user. This could be the first tab they opened, or the first device they came online from:
val listBy = presence.listBy { it.value["metas"]!!.first() }
(NOTE: The underlying behavior is a map transform on the presence.state. You are mapping the state dictionary into whatever datastructure suites your needs)