如何从Firebase检索列表避免异步 [英] How to retrieve a List from Firebase avoid asynchronous

查看:47
本文介绍了如何从Firebase检索列表避免异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,当我们从Firebase检索数据时,它将是异步的,因此通常我会将所有代码放入addChildEventListener内,例如我想在下面对userList进行排序的示例.但是我很困惑,如果List真的很大,例如百万用户,那么这意味着方法sortUser(user)将被称为百万次?谁能向我解释一下,我是Firebase的新手

I know that when we retrieve data from Firebase ,it will be asynchronous, so ussally i will put all the code inside addChildEventListener, like example i want to sort userList below. But i am confused, if the List is really big, like million Users, so it means the method sortUser(user) will be called million times ? Can anyone explain this to me, I'm new to firebase

myRef.child("User").addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            User user= dataSnapshot.getValue(User.class);
            userList.add(user);
            sortUser(userList);
        }
        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

推荐答案

您当前使用的是ChildEventListener,这意味着您的onChildAdded会立即为每个子节点调用,然后在添加新的子节点时调用.确实可能有很多调用.

You currently use a ChildEventListener, which means your onChildAdded gets called for each child node immediately and then later whenever a new child is added. This indeed can be a lot of invocations.

如果使用ValueEventListener,则其onDataChange将仅针对初始数据(无论有多少个子节点)被调用一次,然后为每次更改被调用一次.

If you use a ValueEventListener, its onDataChange will only be called once for the initial data (no matter how many child nodes there are), and then once for each change.

通过在当前设置中添加ValueEventListener,可以使事情保持简单:将子节点添加到灯光中,就像您已经在做的一样,但只能在onDataChange中排序.

By adding a ValueEventListener to your current set up, you can keep things simple: add the child nodes to the lit like you're already doing, but only sort in onDataChange.

myRef.child("User").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
      sortUser(userList);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
};

Firebase只会同步一次User节点的数据,即使您有两个侦听器也是如此.

Firebase will only synchronize the data for the User node once, even when you have two listeners on it.

这篇关于如何从Firebase检索列表避免异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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