等着回来,好吗?

时间:2014-01-10 22:40:22

标签: java firebase

第一个firebase调用的主要代码:

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

对于维护和可读性,对我来说更清楚:

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

感谢您的回复

1 个答案:

答案 0 :(得分:5)

异步回调几乎总是等待等待。特别是你正在使用的忙碌等待。

我发现你的回调代码实际上更清晰了。