2

I am storing a score for each user of my application in firebase.

user {
       name;
       score;
 }

I want to show a leaderboard with the names and scores of the top 10 users (and keep it updated in real time). What is the best way to achieve this?

pdeva
  • 43,605
  • 46
  • 133
  • 171

1 Answers1

4

Check out the leaderboard example for a way to do this: https://www.firebase.com/tutorial/#example/leaderboard

The basic principle is that in addition to setting the name and score in a user object, you can use setWithPriority to also set a priority for it. Priority in this particular case can be the user's score (if its numeric, it will automatically be sorted for you). You can then use the .limit(10) query to get a list of top 10 users.

You'll also have to implement the child_added, child_changed and child_removed events to handle the cases of a new user entering the top 10, someone changing position and someone leaving the top 10 list respectively.

Anant
  • 7,408
  • 1
  • 30
  • 30
  • If you have existing records that were inserted without using setWithPriority, how would you either a) retrofit them, or b) sort them without that being set? – KevDog Apr 14 '14 at 18:52