我需要在内部foreach完成之后并将所有数据添加到列表中,然后发送到接口
  
  但是当但仅此行“ view.setOrders(orderList);”下面的“ orderList.add(order);”
  
  我的代码运行正常,但不是那不是性能,我需要最好的方法来收集列表,然后发送到接口。


public ListenerRegistration getOrders() {

        view.showLoading();

       ListenerRegistration listenerRegistration = refOrders.addSnapshotListener((queryDocumentSnapshots, e) -> {

            view.hideLoading();

            if (e != null) {
                view.onErrorMessage(e.getMessage());
            } else {
                List<Order> orderList = new ArrayList<>();
                for (QueryDocumentSnapshot snapshot : queryDocumentSnapshots) {

                    Order order = snapshot.toObject(Order.class);
                    order.setOrderId(snapshot.getId());

                    refUsers.document(order.getPhone()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                            if (task.isSuccessful()) {
                                User user = task.getResult().toObject(User.class);
                                order.setName(user.getName());
                                order.setAddress(user.getAddress());
                                orderList.add(order);

                            }


                        }
                    });
                }

                //Here Back List size = 0
                view.setOrders(orderList);


            }
        });

       return listenerRegistration;

    }

最佳答案

由于get()方法是异步的,这意味着CompletionListener之后的代码将首先执行,然后在检索数据之后,将执行listener

因此,要解决此问题,请在view.setOrders(orderList);内添加以下行CompletionListener

if (task.isSuccessful()) {
 User user = task.getResult().toObject(User.class);
 order.setName(user.getName());
 order.setAddress(user.getAddress());
 orderList.add(order);
view.setOrders(orderList);

10-02 03:17