Subscribe to changes

Adamite database is real time. You can subscribe to snapshots on a document or a collection and get notified when any changes are made.

Subscribing to collections

You can call the onSnapshot method on a collection reference (including a collection reference with queries, orderings, or limits) to be notified when documents within that collection change.

const ref =
  adamite()
    .database()
    .collection("proejcts");

ref.onSnapshot((snap) => {
  console.log(snap.docs.length);
});

Subscribing to documents

You can call the onSnapshot method on a document reference to be notified when that document changes.

const ref =
  adamite()
    .database()
    .collection("proejcts")
    .ref("documentId");

ref.onSnapshot((snap) => {
  console.log(snap.data);
});

Unsubscribing from notifications

On both a collection and document reference, the onSnapshot method returns a function which can be called to unsubscribe from updates.

const unsubscribe = ref.onSnapshot((snap) => {
  // ...
});

unsubscribe();

Getting detailed info about what changed

When the callback passed to onSnapshot is called, is is provided an up to date snapshot of the data. It is also provided detailed information about the change that happened on the document.

ref.onSnapshot((snap, change) => {
  // inspect the previous value, will be undefined for creations
  const oldValue = change.oldSnapshot;
  
  // inspect the new value, will be undefined for deletions
  const newValue = change.newSnapshot;
  
  // determine change type (can be "create", "update", or "delete")
  const changeType = change.changeType;
});

Stream changes directly

The onSnapshot method fetches an initial snapshot of the data before subscribing and reconstructs snapshots of the data (including the entire collection in some cases) whenever a document changes.

In most cases, this is fine, but when dealing with large or rapidly updating sets of data, you may want to stream changes directly and handle them more efficiently. You can use the stream method on a collection or document reference to do this.

const unsubscribe = ref.stream((change) => {
  // inspect the previous value, will be undefined for creations
  const oldValue = change.oldSnapshot;
  
  // inspect the new value, will be undefined for deletions
  const newValue = change.newSnapshot;
  
  // determine change type (can be "create", "update", or "delete")
  const changeType = change.changeType;
});

Last updated