Live Query
Description — Working with Couchbase Lite’s data model — Querying database data using live queries
Related Content — Predictive Query | Indexing | Queries
A live query stays active and monitors the database for changes. A live query is a great way to build reactive user interfaces, especially table/list views, that keep themselves up to date. For example, as the replicator runs and pulls new data from the server, a live query-driven UI will automatically update to show the data without the user having to manually refresh. This helps your app feel quick and responsive.
Query query = QueryBuilder
.select(SelectResult.all())
.from(DataSource.database(database));
// Adds a query change listener.
// Changes will be posted on the main queue.
ListenerToken token = query.addChangeListener(change -> {
for (Result result : change.getResults()) {
Log.d(TAG, "results: " + result.getKeys());
/* Update UI */
}
});
// Start live query.
query.execute(); (1)
1 | To start a live query, you must call query.execute() .
This will immediately execute the query and post the result to the change listener.
When there’s a change it re-runs itself automatically, and posts the new query result to any observers (change listeners). |
The following example stops the live query with the token from the previous example.
query.removeChangeListener(token);