2

Some main code with the first firebase call:

     refFB.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot snapshot, String previousChildName) {
                FirebaseReq fbReq = snapshot.getValue(FirebaseReq.class);
                service(fbReq);
            }
...
        });

For maintanance and readability is for me much more clear this:

Run service(fbReq) in new thread.

 public void service(FirebaseReq firebaseReq) {
            value = dao(firebaseReq);
            /*some other code which use value*/
 }

public String dao(FirebaseReq firebaseReq) {
        String result = null;
        //the second firebase call
        childRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
               result = snapshot.getName();
            }
          ...
       });
        while (result== null){
        }   
        return result;
}

Or is better avoid threads and waiting loop, but with unreadability code:

 public void service(FirebaseReq firebaseReq) {
     ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
               /*some other code which use value*/
            }
          ...
       });
     dao(firebaseReq,valueEventListener);              
 }

public String dao(FirebaseReq firebaseReq,ValueEventListener valueEventListener) {
        //the second firebase call
        childRef.addListenerForSingleValueEvent(valueEventListener);
}

Thanks for reply

Casero
  • 322
  • 2
  • 12
  • 3
    A loop while `while (result == null) { }` could chew up a lot of processor time. If you decide to do it this way, consider using methods like [wait](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait()) and [notify](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#notify()) instead of a loop. – ajb Jan 10 '14 at 23:04

1 Answers1

5

Async callbacks are almost always preferred to a wait. Especially a busy wait as you are using.

I find your callback code cleaner in fact.

Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79