manhtuan21
manhtuan21

Reputation: 3430

How to retrieve a List from Firebase avoid asynchronous

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) {

        }
    });

Upvotes: 0

Views: 324

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

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.

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.

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 will only synchronize the data for the User node once, even when you have two listeners on it.

Upvotes: 1

Sebin Benjamin
Sebin Benjamin

Reputation: 1898

You should probably retrieve the data sorted server side by using order-by methods and then listen to that one.

var userRef = firebase.database().ref('posts').orderByChild('Users');

If I guess correctly, you would not need separate sorting client side.

You can also filter data. Do refer the docs

Upvotes: 1

Related Questions