具有第一个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);
}
.

感谢回复

有帮助吗?

解决方案

异步回调几乎始终是等待的。特别是在你使用时忙碌。

我发现你的回调代码清洁剂实际上。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top