Live Queries
Description — Couchbase mobile database live query concepts
Overview
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.
CBLQuery *query = [CBLQueryBuilder select:@[[CBLQuerySelectResult all]]
from:[CBLQueryDataSource database:database]];
// Adds a query change listener.
// Changes will be posted on the main queue.
id<CBLListenerToken> token = [query addChangeListener:^(CBLQueryChange * _Nonnull change) {
for (CBLQueryResultSet *result in [change results]) {
NSLog(@"%@", result);
/* Update UI */
}
}];
// Start live query.
[query execute: &error]; (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 removeChangeListenerWithToken:token];