1

As mentioned in docs, it's better to fetch additional data, than nest objects in database.

According to this, how can I ensure that all data came?

I came up to this solution, but I'm not sure if this will work.

mPetsReference.addValueEventListener(new ValueEventListener() {
    private List<Pair<Pet, Owner>> mData;
    private long mChildrenCount;
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        mData = new ArrayList<>();
        mChildrenCount = dataSnapshot.getChildrenCount();
        for (DataSnapshot data : dataSnapshot.getChildren()) {
            Pet pet = data.getValue(Pet.class);
            mOwnersReference.child(pet.getOwnerId())
                    .addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            mData.add(new Pair<>(pet, dataSnapshot.getValue(Owner.class)));
                            if (mData.size() == mChildrenCount) {
                                everythingCame();
                            }
                        }
                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            mChildrenCount--;
                            if (mData.size() == mChildrenCount) {
                                everythingCame();
                            }
                        }
                    });
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
    }
});
AL.
  • 36,815
  • 10
  • 142
  • 281
Nominalista
  • 4,632
  • 11
  • 43
  • 102
  • Your logic seems fine to me. Are you having any problems? – Frank van Puffelen Dec 07 '16 at 20:09
  • For my test I haven't noticed problems, wondering if there is better solution. I will use your attention and please see my another question: http://stackoverflow.com/questions/41020787/valueeventlistener-vs-childeventlistener-for-recyclerview-in-android ;) – Nominalista Dec 07 '16 at 20:22
  • You might find this answer interesting, although it is overkill for what you need: http://stackoverflow.com/a/38188683/4815718 – Bob Snyder Dec 07 '16 at 23:29
  • @qbix don't let Doug hear that you consider his solution overkill. ;-) – Frank van Puffelen Dec 08 '16 at 07:29
  • @frank-van-puffelen everyone took it as a joke, of course it's not overkill ;D – Nominalista Dec 08 '16 at 07:32
  • If you decide to use tasks, [Doug's blog series on Tasks](https://firebase.googleblog.com/2016/09/become-a-firebase-taskmaster-part-1.html) is a great resource. – Bob Snyder Dec 08 '16 at 13:57
  • 1
    @FrankvanPuffelen: I'll hope Doug is too busy working on his next Firebase Blog post to notice. His blog series on Tasks is really informative and entertaining. Great music videos! ;-) – Bob Snyder Dec 08 '16 at 14:51

0 Answers0