Live Queries

    +
    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.

    var query = QueryBuilder
        .Select(SelectResult.All())
        .From(DataSource.Database(db));
    
    // Adds a query change listener.
    // Changes will be posted on the main queue.
    var token = query.AddChangeListener((sender, args) =>
    {
        var allResult = args.Results.AllResults();
        foreach (var result in allResult) {
            Console.WriteLine(result.Keys);
            /* 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);
    query.Dispose();