dehaze

Live Query

Live query

When you make a live query request to Space Cloud, it first pushes down the initial data in the result set one by one and there after notifies you of any changes that happens to your result set.

Example: Live query to the list of pokemons caught by a trainer:

# Note: Only one single top level field is allowed in subscriptions

subscription {
  caught_pokemons(
    where: {trainer_id: "1"}
  ) @mongo {
    type
    payload {
      name
    }
    docId # This is the primary key of the changed document 
  }
}
const whereClause = cond("trainer_id", "==", "1")

// Callback for data changes:
const onSnapshot  = (docs, type, doc) => {
   // docs is the entire result set maintained by the client SDK
   // whereas doc is the concerned doc
   console.log(docs, type, doc)
}

// Callback for error while subscribing
const onError = (err) => {
   console.log('Live query error', err)
}

let subscription = db.liveQuery("caught_pokemons")
  .where(whereClause).subscribe(onSnapshot, onError)

// Unsubscribe to changes
if (on some logic) {
  subscription.unsubscribe()
}

Data pushed down in live query have the following fields:

  • type: The type of operation which has resulted into Space Cloud pushing down data. Possible values are - initial, insert, update, and delete. initial is only applicable when Space Cloud is pushing the initial data down.
  • payload: The concerned document/object. null for delete operation.
  • docId: The unique id of the corresponding document/object. In case of MongoDB it’s the _id field of the concerned document and in case of SQL databases, it’s the id of the concerned record.

Subscribing to changes only

In case you are interested in only the changes and not the initial values, pass the options.skipInitial argument to the live query:

subscription {
  caught_pokemons @mongo (
    where: {trainer_id: $trainerId},
    options: {skipInitial: true}
  ){
    type
    payload {
      name
    }
    docId
  }
}
const whereClause = cond("trainer_id", "==", "1")

// Callback for data changes:
const onSnapshot  = (docs, type, doc) => {
   // docs is the entire result set maintained by the client SDK
   // whereas doc is the concerned doc
   console.log(docs, type, doc)
}

// Callback for error while subscribing
const onError = (err) => {
   console.log('Live query error', err)
}

let subscription = db.liveQuery("caught_pokemons")
  .options({skipInitial: true})
  .where(whereClause).subscribe(onSnapshot, onError)

// Unsubscribe to changes
if (on some logic) {
  subscription.unsubscribe()
}

Have a technical question?

Improve the docs!