Firebase network connection loss onDisconnect handler trouble

1.3k views Asked by At

I'm having an issue with trying to handle network connection loss reconnects in Firebase.

When the connection gets reestablished it works like it should and writes the user data back to firebase again, but then it removes it again immediately. From what I can tell the onDisconnect.remove() function seems to be firing out of order.

Here's my code, maybe someone can spot the problem or suggest a better way to handle a network connection loss:

    var userListRef = new Firebase('https://myrecovery.firebaseIO.com/tsmusers/');
    var meetingId = $('#meetingIdInput').val();
    var myUserId = $('#myIdInput').val();
    var userName = $('#nameInput').val();
    var avatar = $('#myImage').val();
    var myUserRef = new Firebase('https://myrecovery.firebaseIO.com/tsmusers/' + meetingId + '/users/' + myUserId);
    var usersRef = new Firebase('https://myrecovery.firebaseIO.com/tsmusers/' + meetingId + '/users');
    var connectedRef = new Firebase("https://myrecovery.firebaseIO.com/.info/connected");

    // CHECK FIREBASE PRESENSE
    connectedRef.on("value", function(isOnline) {
        if (isOnline.val() === true) {
            console.log('Connected to Firebase');
            // FIRE FUNCTION TO CONNECT TO THE MEETING
            connectToMeeting();
        } else {
            console.log('Disconnected from Firebase');
            // REMOVE USER FROM FIREBASE ON DISCONNECT
            myUserRef.onDisconnect().remove();
        }
    });

    // CONNECT TO THE MEETING
    function connectToMeeting() {
        // ADD USER TO FIREBASE MEETING->USER TABLE
        myUserRef.set({userId: myUserId, userName: userName, avatar: avatar});

        // CONNECT TO OPENTOK
        session.connect(apiKey, token);
    }

    // ADD USER TO ATTENDEE SECTION ON CONNECTION
    usersRef.on('child_added', function(snapshot) {
        var user = snapshot.val();
        displayConnectedUser(user.userId, user.avatar, user.userName);
    });
    function displayConnectedUser(userId, avatar, userName) {
        $('#attendees').prepend('<div id="attendee_' + userId + '" class="attendee_box">' + avatar + '<br />' + userName + '</div>');
    }
1

There are 1 answers

1
Anant On BEST ANSWER

You have to use onDisconnect() when you are online. The client can't communicate with the server when it's offline so the onDisconnect() operation won't take place until you are next online. You can change the code to:

connectedRef.on("value", function(isOnline) {
  if (isOnline.val() === true) {
    console.log('Connected to Firebase');
    // FIRE FUNCTION TO CONNECT TO THE MEETING
    connectToMeeting();
    // REMOVE USER FROM FIREBASE ON DISCONNECT
    myUserRef.onDisconnect().remove();
  }
}

Hope this helps!