Skip to content Skip to sidebar Skip to footer

How Do I Rework These Firebase Valueeventlisteners To Be Readable?

If there's something I'm struggling with it's how to write good looking code with asynchronous calls to Firebase. Below is the code for one of my functions that retrieves all users

Solution 1:

I write my code like this so it easier to read:

onCreate() {
    dataRef.addListenerForSingleValueEvent(newValueEventListener() {
        @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
            doSomething(dataSnapshot);
            ...
        }
        ...
    }
}

doSomething(DataSnapshot dataSnapshot) {
    ...
}

If I want a Firebase call to run after another Firebase call, I place it inside doSomething.

BUT, if that call doesn't have to run after each other (like "get current user" and "get all user" call from your sample code), I made it like this:

boolean firstCallDone = false;
boolean secondCallDone = false;

DataSnapshot firstDataSnapshot = null;
DataSnapshot secondDataSnapshot = null;

onCreate() {
    firstRef.addListenerForSingleValueEvent(newValueEventListener() {
        @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
            firstCallDone = true;
            firstDataSnapshot = dataSnapshot;

            if (firsCallDone && secondCallDone)
                doSomething();
        }
        ...
    }
    secondRef.addListenerForSingleValueEvent(newValueEventListener() {
        @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
            secondCallDone = true;
            secondDataSnapshot = dataSnapshot;

            if (firsCallDone && secondCallDone)
                doSomething();
        }
        ...
    }
}

doSomething() {
    // do something with firstDataSnapshot and secondDataSnapshot
    ...
}

Hope this help.

Post a Comment for "How Do I Rework These Firebase Valueeventlisteners To Be Readable?"