LiveCounter
LiveCounter is a synchronized numerical counter that supports increment and decrement operations. It ensures that all updates are correctly applied and synchronized across users in realtime, preventing inconsistencies when multiple users modify the counter value simultaneously.
Create LiveCounter
A LiveCounter
instance can be created using the channel.objects.createCounter()
method. It must be stored inside a LiveMap
object that is reachable from the root object.
channel.objects.createCounter()
is asynchronous, as the client sends the create operation to the Ably system and waits for an acknowledgment of the successful counter creation.
Optionally, you can specify an initial value when creating the counter:
Get counter value
Get the current value of a counter using the LiveCounter.value()
method:
Subscribe to data updates
You can subscribe to data updates on a counter to receive realtime changes made by you or other clients.
Subscribe to data updates on a counter using the LiveCounter.subscribe()
method:
The update object provides details about the change, such as the amount by which the counter value was changed.
Example structure of an update object when the counter was incremented by 5:
Or decremented by 10:
Unsubscribe from data updates
Use the unsubscribe()
function returned in the subscribe()
response to remove a counter update listener:
Use the LiveCounter.unsubscribe()
method to deregister a provided listener:
Use the LiveCounter.unsubscribeAll()
method to deregister all counter update listeners:
Update LiveCounter
Update the counter value by calling LiveCounter.increment()
or LiveCounter.decrement()
. These operations are synchronized across all clients and trigger data subscription callbacks for the counter, including on the client making the request.
These operations are asynchronous, as the client sends the corresponding update operation to the Ably system and waits for acknowledgment of the successful counter update.
Subscribe to lifecycle events
Subscribe to lifecycle events on a counter using the LiveCounter.on()
method:
Read more about objects lifecycle events.
Unsubscribe from lifecycle events
Use the off()
function returned in the on()
response to remove a lifecycle event listener:
Use the LiveCounter.off()
method to deregister a provided lifecycle event listener:
Use the LiveCounter.offAll()
method to deregister all lifecycle event listeners: