0

I am working on using the Firebase database in a Unity project. I read that you want to structure your database as flat as possible for preformance so for a leaderboard I am structuring it like this

users
     uid
         name
     uid
         name
leaderboard
     uid
        score
     uid
        score

I want a class that can get this data and trigger a callback when it is done. I run this in my constructor.

root.Child("leaderboard").OrderByChild("score").LimitToLast(_leaderboardCount).ValueChanged += onValueChanged;

To trigger the callback with the data I wrote this.

void onValueChanged(object sender, ValueChangedEventArgs args)
{
    int index = 0;
    List<string> names = new List<string>();
    foreach (DataSnapshot snapshot in args.Snapshot.Children)
    {
            root.Child("players").Child(snapshot.Key).GetValueAsync().ContinueWith(task =>
            {
                if (task.Result.Exists)
                {
                    names.Add(task.Result.Child("name").Value.ToString());

                    index++;
                    if (index == args.Snapshot.ChildrenCount)
                    {
                        _callback(names);
                    }
                }
            });
        }
    }

I am wondering if there is a better way to do this that I am missing? I'm worried if the tasks finish out of order my leaderboard will be jumbled. Can I get the names and scores in one snapshot?

Thanks!

WebCam
  • 27
  • 5

1 Answers1

2

You can only load:

  • a single complete node
  • a subset of all child nodes matching a certain condition under a single node

It seems that what you are trying to do is get a subset of the child nodes from multiple roots, which isn't possible. It actually looks like you're trying to do a join, which on Firebase is something you have to do with client-side code.

Note that loading the subsequent nodes is often a lot more efficient than developers expect, since Firebase can usually pipeline the requests (everything goes over a single web socket connection). For more on this, see http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807