Observable Queries

For @Query-annotated functions returning LiveData, Flow, Observable, or Flowable, Room will deliver changes over time. You will get one result from the query initially. If you continue to observe the reactive data source, though, and you modify the database via Room, you will get fresh results delivered to you automatically via the reactive data source.

So, for example, if you have a fragment observing a query and using that data to populate a list, and other code in that fragment inserts a new row into the database, your fragment will get a fresh query result without having to manually re-request it.

This is very convenient in many cases. Bear in mind, though, that you just get a fresh result without any context. So, in the example from the previous paragraph, while you get a fresh query result, you are not told exactly what changed in that result… if anything. For example, you might be inserting a row that is not included in the query result because it failed to match a WHERE clause.

Conversely, you might get a new result delivered to you where nothing actually changed. Suppose you have an outstanding query with WHERE price > 10 in the SQL, and you insert a new row to that table where price is 5. Room will deliver you a fresh result representing the data change in the table… but since this new row does not match your WHERE clause, the “fresh” result will be the same as the last result. You could use distinctUntilChanged() on Flow or Observable to filter out those duplicate results, if desired.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.