skip to Main Content

The title might be worded weirdly or unclear, but I am creating a game using android studio and Kotlin as the language. I have a repository that retrieves the score to the game (also stores it):

  val readAllData: LiveData<List<ScoreDB>> = scoreDao.getScore()

Then in my leaderboard composable function I have:

    val scoreList : LiveData<List<ScoreDB>> = vm.readAllData

I want to filter out this list to display the top 10 scores. After scoreList is filtered to only the top ten score, I was going to put it in a lazyColumn using something like this:



                //TODO List highest scores from database in this lazycolumn
                items(10){idx->
                    ScoreRow(idx)


                }

I am stuck on how to filter the scoreList to contain only the top 10 scores and then to display them in the lazy column. Thanks for the help

2

Answers


  1. I want to filter out this list to display the top 10 scores.

    OK, so you need

    1. a list
    2. to the sort the list highest to lowest and
    3. to take the first 10 of that:

    So:

    val topTenScores = scoreList  // The live data
        .value // The actual list
        .sortedByDescending { it.score } // The list sorted by ScoreDB.score
        .take(10) // And filtering out the first 10 
    
    Login or Signup to reply.
  2. You can use sortedByDescending() to filter the list, and use take() to get the first 10 elements. If you want to show it, you should create a new LivaData to store your filterd list:

    val topTenScoreList : LiveData<List<ScoreDB>> =
    Transformations.map(scoreList) {
                it.sortedDescending{ s->s.score }.take(10)
    }
    

    And use topTenScoreList to generate columns

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search