Firebase: how to get and set a global index counter?

Can anyone help with analyzing how well this code work distributed across many people while being realtime? I want all the users to be able to update a realtime graph and send values to it.

Each client has a local counter variable:

var count = 0;

Sending a Value:

 $('#addValue').click(function(){
        fbValues.push({ x: count, y: randomNum(30,60)});
 });

Listening for a Child to be addded to firebase:

 fbValues.on("child_added", function(snapshot) {

        count += 1;

        var x_coor = snapshot.val().x;
        var y_coor = snapshot.val().y;

        data.values.push({ x: x_coor, y: y_coor });
        updateGraph();

    });

The issue is probably with the local variables of count and currently the graph works fine for most use cases, but when lots of people start sending data sometimes the count will become out of sequence

I looked up transactions for firebase and I can keep a total count on firebase accurate but I don't see how this will help clients increment their counters correctly.

Answers


Clients may call the transaction method directly.

var fb = new Firebase(URL);
var counterRef = fb.child('counter');
var valsRef = fb.child('values');

$('#addValue').click(function(){
    counterRef.transaction(function(currentVal) {
       return (currentVal||0)+1;
    },
    function(err, success, snap) {
       fbValues.push({ x: snap.val(), y: randomNum(30,60)});
    });
});

Locally, just listen on the counter path for changes:

var counter = 0;
counterRef.on('value', function(snap) {
   counter = snap.val() || 0;
});

Need Your Help

Android: unable to detect outgoing number

android broadcastreceiver

I am unable to detect what is outgoing number, its always giving me null pointer exception when i try to place outgoing call from device. I want to detect outgoing telephone number. Please advise, I

How can I correctly combine multiple boolean postfix expressions?

.net vb.net binary-tree postfix-notation rpn

I've put together some code to convert between postfix and infix and back again. Now I'm trying to take separate postfix expressions and combine them.