2014-01-10 39 views
1

与第一火力点调用一些主要代码:正在等待退货,好吗?

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

对于maintanance和可读性是对我更清楚这一点:

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; 
} 

或者是更好的避免线程和等待循环,但不可读性代码:

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); 
} 

感谢您的回复

+3

while while while(result == null){}'可能会消耗大量的处理器时间。如果您决定这样做,请考虑使用[wait](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait())和[notify ](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#notify())而不是循环。 – ajb

回答

5

异步回调几乎总是首选等待。尤其是您正在使用的繁忙等待。

其实我发现你的回调代码更清洁。

+0

谢谢。有没有使用异步回调的模式?或者我的代码很好? – Casero