在等待返回,好吗?

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

谢谢您的回复

让·贝纳德·佩勒林

异步回调几乎总是比等待更可取。尤其是您正在使用时的繁忙等待。

我发现您的回调代码清理器实际上。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章