Hello, I'm trying to sort a list of news items acc...
# getting-started
n
Hello, I'm trying to sort a list of news items according to their publication date. I tried this code but it does not sort them; I was wondering if someone could please give me a hand to sort them successfully. 🧵
Copy code
is Resource.Success -> {
                        CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>).launch {
                            database.newsFeedDao.deleteFeedsByUrl(url)

                            val sortedResults = resource.result.sortedByDescending { newsFeed ->
                                LocalDateTime.parse(newsFeed.feedItem.pubDate, dateTimeFormatter)
                            }

                            database.newsFeedDao.insertNewsFeeds(sortedResults)
                        }
                    }
y
What error are you getting? A compiler error? Or are they just simply not sorted? Are there multiple newsFeeds inside your
resource.results
? Maybe some example data might help
n
They are simply not sorted in my room database. Yes, there are quite a few.
y
Try a few
print
statements. Also, do they already have an ID before you inset them? If so, you won't see the effect of sorting at all. Sorting impacts insertion order, which should only impact insertion if they don't have an ID
n
image.png
Yes, they have an id
Ah that makes sense
y
Also, does it even matter if they're pre-sorted in the database? Usually, what one does is when you read from the database, you specify some form of
orderBy
clause that orders the items you're reading. You usually shouldn't care whether the database has them in order or not because that can be quite fragile
n
Good point, that's probably where I am going wrong
I don't need to sort them at the level of the database.
Thanks