Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top