A newer version of this documentation is available.

View Latest

Live Query — Working with Queries

      +

      Description — Couchbase Lite database data querying concepts — live queries
      Related Content — Predictive Queries | Indexing | QueryBuilder

      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.

      To activate a LiveQuery just add a change listener to the query statement. It will be immediately active. When a change is detected the query automatically runs, and posts the new query result to any observers (change listeners).

      Example 1. Starting a Live Query
      • Kotlin

      • Java

      val query = QueryBuilder
          .select(SelectResult.all())
          .from(DataSource.database(database)) (1)
      
      // Adds a query change listener.
      // Changes will be posted on the main queue.
      val token = query.addChangeListener { change ->
          change.results?.let {
              for (result in it) {
                  Log.d(TAG, "results: ${result.keys}")
                  /* Update UI */
              }
          } (2)
      }
      Query query = QueryBuilder
          .select(SelectResult.all())
          .from(DataSource.database(database)); (1)
      
      // Adds a query change listener.
      // Changes will be posted on the main queue.
      ListenerToken token = query.addChangeListener(change -> { (2)
          for (Result result : change.getResults()) {
              Log.d(TAG, "results: " + result.getKeys());
              /* Update UI */
          }
      });
      1 Build the query statements
      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
      Example 2. Stop a LIve Query
      • Kotlin

      • Java

      query.removeChangeListener(token)
      query.removeChangeListener(token); (1)
      1 Here we use the change lister token from Example 1 to remove the listener. Doing so stops the live query.

      Using Kotlin Flows and LiveData

      Kotlin developers also have the option of using Flows and Live Data to feed query changes to the UI.

      Define a live query as a Flow returning a LiveData object and activate an Observer in the View onCreate() function.

          var liveQuery: LiveData<List<Any>?>? = null
      
          @ExperimentalCoroutinesApi
          fun watchQuery(query: Query): LiveData<List<Any>?> {
              val queryFlow = query.queryChangeFlow()
                  .map {
                      val err = it.error
                      if (err != null) {
                          throw err
                      }
                      it.results?.allResults()?.flatMap { it.toList() }
                  }
                  .asLiveData()
              liveQuery = queryFlow
              return queryFlow
          }