There are plenty of use cases when mBaaS-powered applications must use a centralized mechanism for incrementing or decrementing a value. There are several approaches for maintaining a counter – some apps use a database, others keep it in the server-side business logic (Cloud Code).
Backendless offers a specialized API for working with atomic counters. The API is cross-platform – any number of different clients (including REST) can work with the same counter and update it concurrently. Every counter in Backendless has a name, which is assigned by the client application. The sample below demonstrates the API for incrementing and retrieving the value of a counter.
IAtomiccounter = Backendless.Counters.of("my counter"); counter.incrementAndGet(new AsyncCallback () { @Override public void handleResponse(Long response) { Log.i( TAG, "Counter value: " + response ); } @Override public void handleFault(BackendlessFault fault) { Log.e( TAG, "Server reported an error: " + fault.getMessage() ); } });
val counter = Backendless.Counters.of("my counter") counter.incrementAndGet(object : AsyncCallback{ override fun handleResponse(response: Int?) { Log.i(TAG, "Counter value: " + response!!) } override fun handleFault(fault: BackendlessFault) { Log.e(TAG, "Server reported an error: " + fault.message) } })
id counter = [Backendless.shared.counters ofCounterName:@"my counter"]; [counter incrementAndGetWithResponseHandler:^(NSInteger counterValue) { NSLog(@"Counter value - %li", (long)counterValue); } errorHandler:^(Fault *fault) { NSLog(@"Error: %@", fault.message); }];
let counter = Backendless.shared.counters.of(counterName: "my counter") counter.incrementAndGet(responseHandler: { counterValue in print("Counter value - \(counterValue)") }, errorHandler: { fault in print("Error: \(fault.message ?? "")") })
const counter = Backendless.Counters.of('my counter') counter.incrementAndGet() .then(counterValue => { console.log(`Counter value - ${ counterValue }`) }) .catch(error => { console.error(`Server reported an error - ${ error.message }`) })
IAtomic counter = Backendless.counters.of("my counter"); counter.incrementAndGet().then((value) { print("Counter value - $value"); });
The API is very easy to use and provides several other features like decrementing a value, performing a conditional update, retrieving the current value, and resetting a counter.