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.

JavaScript

Optionally, you can specify an initial value when creating the counter:

JavaScript

Get counter value

Get the current value of a counter using the LiveCounter.value() method:

JavaScript

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:

JavaScript

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:

JSON

Or decremented by 10:

JSON

Unsubscribe from data updates

Use the unsubscribe() function returned in the subscribe() response to remove a counter update listener:

JavaScript

Use the LiveCounter.unsubscribe() method to deregister a provided listener:

JavaScript

Use the LiveCounter.unsubscribeAll() method to deregister all counter update listeners:

JavaScript

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.

JavaScript

Subscribe to lifecycle events

Subscribe to lifecycle events on a counter using the LiveCounter.on() method:

JavaScript

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:

JavaScript

Use the LiveCounter.off() method to deregister a provided lifecycle event listener:

JavaScript

Use the LiveCounter.offAll() method to deregister all lifecycle event listeners:

JavaScript
Select...