Android中的嵌套Firestore异步侦听器 [英] Nested Firestore asynchronous listeners in Android

查看:131
本文介绍了Android中的嵌套Firestore异步侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在多个Days集合中都有活动"文档,并且需要将所有活动"合并到一个列表中.我以为应该先循环集合,然后再循环活动,最后得到下面的代码,我不知道这是否是组合多个集合的最佳方法.更糟糕的是,我不知道何时可以将我的列表用于所有异步调用. 有什么建议吗?谢谢!

So I have Activities documents in several Days collections and I need to combine all of the Activities in a list. I thought I should loop the collections and then loop the Activities and ended up with the code below which I don't know whether it's the best way to combine multiple collections. Even worse I don't know WHEN my list is ready to be used with all the asynchronous calls. Any advice? Thanks!

db.collection("calendar").get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot ds : task.getResult().getDocuments()) {
                        ds.getReference().collection("thingstodo").get()
                                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                                    @Override
                                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                                        for (DocumentSnapshot ds : task.getResult().getDocuments()) {
                                            ScheduledItem item = ds.toObject(ScheduledItem.class);
                                            itemsList.add(item);
                                        }

                                    }
                                });

                    }
            }
        });

推荐答案

Tasks.whenAllComplete() 在整个设置完成后做出响应.然后,您可以根据需要检查那里所有任务的结果.

The get() method you're using on CollectionReference (which is a subclass of Query) returns a Task that becomes resolved when the document is ready. Instead of adding a listener to that individual Task, collect all the tasks into a List, and pass that to Tasks.whenAllComplete() to respond when the entire set is complete. You can then examine the results of all the tasks there, as needed.

这篇关于Android中的嵌套Firestore异步侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆