A newer version of this documentation is available.

View Latest
March 23, 2025
+ 12

Description — Working with Couchbase Lite’s data model  — Querying database data using live queries
Related Content — Predictive Query | Indexing | Queries

Activating a Live Query

A live query is a query that, once activated, remains active and monitors the database for changes; refreshing the result set whenever a change occurs. As such, it is a great way to build reactive user interfaces — especially table/list views — that keep themselves up to date.

So, a simple use case may be: A replicator running and pulling new data from a server, whilst a live-query-driven UI automatically updates to show the data without the user having to manually refresh. This helps your app feel quick and responsive.

Example 1. Starting a LIve Query
Java
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 -> { (1) for (Result result : change.getResults()) { Log.d(TAG, "results: " + result.getKeys()); /* Update UI */ } }); // Start live query. query.execute(); (1)
1 Build the query statements using the QuerybUilder
2 Activate the live query by attaching a listener.
Save the token in order to detach the listener and stop the query later — se Example 2
3 Start the query
This will immediately execute the live query and post the result to the change listener. When a change is detected the query automatically runs, and posts the new query result to any observers (change listeners).
Example 2. Stop a LIve Query
Java
query.removeChangeListener(token); (1)
1 Here we use the change lister token from Example 1 to remove the listeners. Doing so stops the live query.
Learn more . . .
Dive Deeper . . .