Filtering Our Items
It is entirely possible that a user of this app will have a lot of to-do items. Rather than force the user to have to scroll through all of them in the list, we could offer some options for working with a subset of those items. In this tutorial, we will add a “filter” feature, to allow the user to work with either the outstanding to-do items, the completed items, or all of the items.
In reality, given the scope of this app, we could do all of our filtering in the RosterListFragment
, or perhaps in the RosterMotor
. This is a book sample, and you are not likely to create lots and lots of to-do items.
In theory, though, there could be lots and lots of to-do items. Or, we could have a more complex data model, Or, we could have to call out to a server to do some sort of search, rather than just filtering some subset of model objects already in memory.
So, in this tutorial, we will pretend that we really do need to request a new roster of items from our repository when the user elects to filter (or stop filtering) the list of items. That makes things a bit more complex but a bit more realistic.
This is a continuation of the work we did in the previous tutorial. The book’s GitLab repository contains the results of the previous tutorial as well as the results of completing the work in this tutorial.
Step #1: Adding a Query
Let’s work “back to front”, updating our ToDoEntity.Store
first, before we start changing ToDoRepository
, RosterMotor
, etc.
In terms of the filtering, we need to have a way of asking the ToDoEntity.Store
to give us the items that match our filter criterion: is the to-do item completed or not.
To that end, add this filtered()
function to ToDoEntity.Store
:
@Query("SELECT * FROM todos WHERE isCompleted = :isCompleted ORDER BY description")
fun filtered(isCompleted: Boolean): Flow<List<ToDoEntity>>
filtered()
takes a Boolean
parameter, indicating if we want the completed or outstanding to-do items. We use that in the WHERE
clause by putting :isCompleted
where we want the value to show up. filtered()
otherwise works like all()
, returning our items via a Flow
.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.