0

I have a Room query that I'm running when my app starts.

@Query("SELECT * FROM myTable")
fun get(): LiveData<List<MyItem?>?>

After the query runs, my user will select several filters which should be applied to the tags column of myTable.

I've got another query using String.

@Query("SELECT * FROM myTable WHERE tags LIKE '%' || :filters || '%'")
fun getFilteredByString(filters: Strings): LiveData<List<MyItem?>?>

I've also got a query using Lists.

@Query("SELECT * FROM myTable WHERE tags IN (:filters)")
fun getFilteredByList(filters: List<Strings>): LiveData<List<MyItem?>?>

This is how I've set up my ViewModel:

class MyViewModel(private val application: Application) : ViewModel() {
...
    private val database: MyDatabase = MyDatabase.getDatabase(application)
    private val myDao: MyDao = database.myDao()
    val results = myDao.get()
    val filters = MutableLiveData<List<String>?>()
...
}

How do I switch the value in results to be one of the other two queries?

I've tried several solutions unsuccessfully (e.g. switchMap, @Transaction, MediationLiveData). The solution should be that results is a static variable that is somehow transformed to another query in the ViewModel rather than in the @Composable for the UI.

I looked at this solution, but it seems to involve going outside of the Room library's built-in capabilities, which I wanted to avoid.

  • Based on your answer, it sounds like your question is a duplicate of, "[How to implement a Room LiveData filter](https://stackoverflow.com/questions/65634643/how-to-implement-a-room-livedata-filter)" – Jeremy Caney Mar 07 '23 at 01:43

1 Answers1

0

I found two solutions:

  1. Removing LiveData from my DAO.
  2. Using filtering within my LazyColumn, so I didn't even have to update my query (way faster computationally).

BONUS: Sorting is also possible on LiveData using Comparator.